-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryTracker.h
More file actions
44 lines (37 loc) · 1.08 KB
/
MemoryTracker.h
File metadata and controls
44 lines (37 loc) · 1.08 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
#ifndef MEMORY_TRACKER_H
#define MEMORY_TRACKER_H
#include <cstdlib>
#include <iostream>
#include <mutex>
class MemoryTracker {
private:
inline static size_t totalMemory = 0;
inline static size_t peakMemory = 0;
inline static std::mutex memMutex;
public:
// Function to allocate memory and track it
static void* allocate(size_t size) {
std::lock_guard<std::mutex> lock(memMutex);
totalMemory += size;
peakMemory = std::max(peakMemory, totalMemory);
return std::malloc(size);
}
// Function to deallocate memory and update the tracker
static void deallocate(void* ptr, size_t size) {
std::lock_guard<std::mutex> lock(memMutex);
totalMemory -= size;
std::free(ptr);
}
// Reset memory tracking
static void reset() {
std::lock_guard<std::mutex> lock(memMutex);
totalMemory = 0;
peakMemory = 0;
}
// Get the current peak memory usage
static size_t getPeakMemoryUsage() {
std::lock_guard<std::mutex> lock(memMutex);
return peakMemory;
}
};
#endif