-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_profiling.cpp
More file actions
34 lines (28 loc) · 885 Bytes
/
memory_profiling.cpp
File metadata and controls
34 lines (28 loc) · 885 Bytes
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
#include "memory_profiling.hpp"
#include <iostream>
#include <iomanip>
#ifdef ENABLE_MEMORY_PROFILING
size_t allocated_memory = 0;
void* operator new(std::size_t sz){
void *out = std::malloc(sz+sizeof(size_t));
*static_cast<size_t*>(out) = sz;
allocated_memory += sz;
return static_cast<void*>(static_cast<size_t*>(out) + 1);
}
void operator delete(void* ptr) noexcept{
if (ptr == NULL) return;
size_t *start_ptr = static_cast<size_t*>(ptr) - 1;
allocated_memory -= *start_ptr;
std::free(static_cast<void*>(start_ptr));
}
std::array<std::string, 4> sizes {"B", "KB", "MB", "GB"};
void print_mem_usage(const std::string &id) {
size_t k = 0;
double mem = allocated_memory;
while (mem >= 1000) {
mem /= 1000;
k++;
}
std::cout << "Usage(" << id << "): " << std::setprecision(4) << mem << sizes[k] << std::endl;
}
#endif