How to get the cpu usage? I found some piece of code from google, but they are not very accurate, maybe I used them in the wrong way.
Here's my code:
#include <windows.h>
#include <stdio.h>
struct CpuUsage {
ULARGE_INTEGER lastCPU;
ULARGE_INTEGER lastSysCPU;
ULARGE_INTEGER lastUserCPU;
int numProcessors;
HANDLE self;
CpuUsage() {
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
numProcessors = sysInfo.dwNumberOfProcessors;
}
void init() {
FILETIME ftime, fsys, fuser;
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));
}
double getCurrentValue() {
FILETIME ftime, fsys, fuser;
ULARGE_INTEGER now, sys, user;
double percent;
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;
}
};
void do_expensive_calculation() {
int x = 2;
for(int i = 0; i < 1000000; i++) {
x *= 2;
}
}
int main() {
CpuUsage usage;
while(true) {
usage.init(); // same result if put this line out of the while loop
do_expensive_calculation();
double cpuUsage = usage.getCurrentValue();
printf("cpu: %.1f\n", cpuUsage);
Sleep(50);
}
}
a sample output:
cpu: 0.0
cpu: 14.2
cpu: 0.0
cpu: 14.2
cpu: 0.0
cpu: 13.9
cpu: 0.0
cpu: 13.9
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 0.0
cpu: 13.9
It does the same thing in each loop, why the output is different.