2024-11-03 11:37:31 +01:00

83 lines
2.0 KiB
C++

#include "Perfs.hpp"
#if defined(__MINGW32__) || defined(_MSC_VER)
#include <windows.h>
#include <psapi.h>
#else
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#endif
#if !(defined(__MINGW32__) || defined(_MSC_VER))
static int parseLine(char* line) {
// This assumes that a digit will be found and the line ends in "kB".
int i = strlen(line);
const char* p = line;
while (*p <'0' || *p > '9') p++;
line[i-3] = '\0';
i = atoi(p);
return i;
}
// Returned value in KB!
static int getLinuxVirtualMemUsage() {
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmSize:", 7) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result;
}
// Returned value in KB!
static int getLinuxPhysicalMemUsage() {
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmRSS:", 6) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result;
}
#endif
// Returned value in KB!
const size_t PerfsGetVirtMem(void) {
size_t out;
#if defined(__MINGW32__) || defined(_MSC_VER)
PROCESS_MEMORY_COUNTERS_EX memCounter;
GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&memCounter, sizeof(memCounter));
out = memCounter.PrivateUsage / 1000;
#else
out = getLinuxVirtualMemUsage();
#endif
return out;
}
// Returned value in KB!
const size_t PerfsGetPhysMem(void) {
size_t out;
#if defined(__MINGW32__) || defined(_MSC_VER)
PROCESS_MEMORY_COUNTERS_EX memCounter;
GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&memCounter, sizeof(memCounter));
out = memCounter.WorkingSetSize / 1000;
#else
out = getLinuxPhysicalMemUsage();
#endif
return out;
}