MiniOB 1
MiniOB is one mini database, helping developers to learn how database works.
载入中...
搜索中...
未找到
memtracer.h
1/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
2miniob is licensed under Mulan PSL v2.
3You can use this software according to the terms and conditions of the Mulan PSL v2.
4You may obtain a copy of Mulan PSL v2 at:
5 http://license.coscl.org.cn/MulanPSL2
6THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
7EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
8MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
9See the Mulan PSL v2 for more details. */
10
11#pragma once
12
13#include <cstdlib>
14
15#include "memtracer/common.h"
16#include "common/lang/thread.h"
17#include "common/lang/atomic.h"
18#include "common/lang/mutex.h"
19
20namespace memtracer {
21
22#define MT MemTracer::get_instance()
23
24// MemTracer is used to monitor MiniOB memory usage;
25// it is used to run and debug MiniOB under memory-constrained conditions.
26// MemTracer statistics memory allocation in MiniOB processes by
27// hooking memory alloc/free functions.
28// More detail can be found at docs/src/game/miniob-memtracer.md
30{
31public:
32 static MemTracer &get_instance();
33
34 MemTracer() = default;
35
36 static void __attribute__((constructor)) init();
37
38 static void __attribute__((destructor)) destroy();
39
40 size_t allocated_memory() const { return allocated_memory_.load(); }
41
42 size_t meta_memory() const { return ((alloc_cnt_.load() - free_cnt_.load()) * sizeof(size_t)); }
43
44 size_t print_interval() const { return print_interval_ms_; }
45
46 size_t memory_limit() const { return memory_limit_; }
47
48 bool is_stop() const { return is_stop_; }
49
50 void set_print_interval(size_t print_interval_ms) { print_interval_ms_ = print_interval_ms; }
51
52 inline void add_allocated_memory(size_t size) { allocated_memory_.fetch_add(size); }
53
54 void set_memory_limit(size_t memory_limit)
55 {
56 call_once(memory_limit_once_, [&]() { memory_limit_ = memory_limit; });
57 }
58
59 void alloc(size_t size);
60
61 void free(size_t size);
62
63 inline void init_hook_funcs() { call_once(init_hook_funcs_once_, init_hook_funcs_impl); }
64
65private:
66 static void init_hook_funcs_impl();
67
68 void init_stats_thread();
69
70 void stop();
71
72 static void stat();
73
74private:
75 bool is_stop_ = false;
76 atomic<size_t> allocated_memory_{};
77 atomic<size_t> alloc_cnt_{};
78 atomic<size_t> free_cnt_{};
79 once_flag init_hook_funcs_once_;
80 once_flag memory_limit_once_;
81 size_t memory_limit_ = UINT64_MAX;
82 size_t print_interval_ms_ = 0;
83 thread t_;
84};
85} // namespace memtracer
Definition: memtracer.h:30