-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofile-mem.cpp
More file actions
88 lines (72 loc) · 1.86 KB
/
profile-mem.cpp
File metadata and controls
88 lines (72 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "profile-mem.hpp"
#include <unistd.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <thread>
#include "utils.hpp"
namespace profile::mem {
#ifndef ENABLE_PROFILE
#define ENABLE_PROFILE true
#endif
bool profile_mem_enabled = false;
const char* MEM_PROFILE_FILENAME = "memory_status.log";
void init_mem(const char* filename = "memory_status.log") {
MEM_PROFILE_FILENAME = filename;
}
void start() {
fprintf(stderr, "Profile-mem.cpp: memory usage profile: %d\n",
ENABLE_PROFILE);
#if (ENABLE_PROFILE)
profile_mem_enabled = true;
#endif
}
void stop() {}
struct MemoryProfile {
bool is_running = false;
std::thread t_monitor;
void run() {
while (is_running && !profile_mem_enabled) {
my_usleep(500);
}
if (!is_running) return;
FILE* fout = fopen(MEM_PROFILE_FILENAME, "w");
fprintf(stderr, "MemoryProfile Starts\n");
while (is_running) {
FILE* f = fopen("/proc/self/status", "r");
if (!f) {
fprintf(stderr, "fopen failed\n");
}
char line[255];
while (f && fgets(line, sizeof(line), f)) {
if (!strncmp(line, "VmRSS", 5)) {
fprintf(fout, "%s", line);
}
}
fclose(f);
my_usleep(1000);
}
fflush(fout);
fclose(fout);
}
MemoryProfile() {
#if (ENABLE_PROFILE)
is_running = true;
t_monitor = std::thread([&]() { run(); });
#else
profile_mem_enabled = false;
#endif
}
~MemoryProfile() {
#if (ENABLE_PROFILE)
is_running = false;
t_monitor.join();
fprintf(stderr, "MemoryProfile Stopped\n");
#endif
}
} g_mem_profile;
} // namespace profile::mem