SleakEngine 1.0.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
SystemMetrics.cpp
Go to the documentation of this file.
2
3#ifdef PLATFORM_WIN
4#include <windows.h>
5#include <psapi.h>
6#include <pdh.h>
7#pragma comment(lib, "pdh.lib")
8#pragma comment(lib, "psapi.lib")
9#endif
10
11#ifdef PLATFORM_LINUX
12#include <cstdio>
13#include <cstring>
14#endif
15
16namespace Sleak {
17
18bool SystemMetrics::s_initialized = false;
19
20#ifdef PLATFORM_WIN
21
22static PDH_HQUERY s_cpuQuery = nullptr;
23static PDH_HCOUNTER s_cpuCounter = nullptr;
24
26 if (s_initialized) return;
27
28 PdhOpenQuery(nullptr, 0, &s_cpuQuery);
29 PdhAddEnglishCounterA(s_cpuQuery,
30 "\\Processor(_Total)\\% Processor Time",
31 0, &s_cpuCounter);
32 PdhCollectQueryData(s_cpuQuery);
33
34 s_initialized = true;
35}
36
38 if (!s_initialized) return;
39
40 if (s_cpuQuery) {
41 PdhCloseQuery(s_cpuQuery);
42 s_cpuQuery = nullptr;
43 s_cpuCounter = nullptr;
44 }
45
46 s_initialized = false;
47}
48
50 SystemMetricsData data;
51 if (!s_initialized) return data;
52
53 // CPU usage
54 PdhCollectQueryData(s_cpuQuery);
55 PDH_FMT_COUNTERVALUE counterVal;
56 PdhGetFormattedCounterValue(s_cpuCounter, PDH_FMT_DOUBLE,
57 nullptr, &counterVal);
58 data.CpuUsagePercent = static_cast<float>(counterVal.doubleValue);
59
60 // RAM usage (process working set)
61 PROCESS_MEMORY_COUNTERS_EX pmc;
62 if (GetProcessMemoryInfo(GetCurrentProcess(),
63 reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmc),
64 sizeof(pmc))) {
65 data.RamUsageMB =
66 static_cast<float>(pmc.WorkingSetSize) / (1024.0f * 1024.0f);
67 }
68
69 return data;
70}
71
72#elif defined(PLATFORM_LINUX)
73
75 s_initialized = true;
76}
77
79 s_initialized = false;
80}
81
83 SystemMetricsData data;
84 if (!s_initialized) return data;
85
86 // RAM usage from /proc/self/status
87 FILE* f = fopen("/proc/self/status", "r");
88 if (f) {
89 char line[256];
90 while (fgets(line, sizeof(line), f)) {
91 if (strncmp(line, "VmRSS:", 6) == 0) {
92 long kb = 0;
93 sscanf(line + 6, "%ld", &kb);
94 data.RamUsageMB = static_cast<float>(kb) / 1024.0f;
95 break;
96 }
97 }
98 fclose(f);
99 }
100
101 return data;
102}
103
104#else
105
107 s_initialized = true;
108}
109
111 s_initialized = false;
112}
113
117
118#endif
119
120} // namespace Sleak
static SystemMetricsData Query()
Reads the current CPU/RAM/GPU usage from the OS.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10