I have been working on my final year project for, the content of which is irrelevant to the problem, but I need to obtain the CPU Usage each frame and the memory usage of the program.
I have implemented a snippet of code I found on Stack Overflow (http://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process) but I have a huge problem.
Quite frequently the GetCPUUsage() returns 0 or INF.
This is obviously because the current and last are the same values.
This is moving into programming territory I know extremely little or absolutely nothing about. What are the potential solutions to this problem, I have no problem implementing a different method of obtaining resource usage if anybody has any suggestions.
The exact code I am using:
#pragma once
/*
http://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process
*/
#include <Windows.h>
#include <Psapi.h>
#pragma comment(lib, "Psapi.lib")
class ResourceUsage
{
private:
PROCESS_MEMORY_COUNTERS pmc;
int numProcessors;
HANDLE self;
ULARGE_INTEGER lastCPU;
ULARGE_INTEGER lastSysCPU;
ULARGE_INTEGER lastUserCPU;
FILETIME ftime, fsys, fuser;
ULARGE_INTEGER now, sys, user;
ResourceUsage()
{
SYSTEM_INFO sysInfo;
FILETIME ftime, fsys, fuser;
GetSystemInfo(&sysInfo);
numProcessors = sysInfo.dwNumberOfProcessors;
GetSystemTimeAsFileTime(&ftime);
memcpy(&lastCPU, &ftime, sizeof(FILETIME));
self = GetCurrentProcess();
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
}
~ResourceUsage(){}
public:
static ResourceUsage& GetSingleton()
{
static ResourceUsage ru;
return ru;
}
SIZE_T GetMemoryUsage(void)
{
GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
return pmc.WorkingSetSize;
}
double GetCPUUsage()
{
double percent = 0.0f;
GetSystemTimeAsFileTime(&ftime);
memcpy(&now, &ftime, sizeof(FILETIME));
GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
memcpy(&sys, &fsys, sizeof(FILETIME));
memcpy(&user, &fuser, sizeof(FILETIME));
percent = (sys.QuadPart - lastSysCPU.QuadPart) +
(user.QuadPart - lastUserCPU.QuadPart);
percent /= (now.QuadPart - lastCPU.QuadPart);
percent /= numProcessors;
lastCPU = now;
lastUserCPU = user;
lastSysCPU = sys;
return percent * 100;
}
};
Thanks in advance.
-MaGuSware