I have a somewhat strange behavior of the code I'm showing below. This code is called repeatedly to measure the current CPU usage in my application (the value measured for all CPU cores):
int get_CPU_Usage(void)
{
//RETURN: = CPU Usage in percent [0 - 100], or
// = -1 if error
int nRes = -1;
FILETIME ftIdle, ftKrnl, ftUsr;
if(GetSystemTimes(&ftIdle, &ftKrnl, &ftUsr))
{
static BOOL bUsedOnce = FALSE;
static ULONGLONG uOldIdle = 0;
static ULONGLONG uOldKrnl = 0;
static ULONGLONG uOldUsr = 0;
ULONGLONG uIdle = ((ULONGLONG)ftIdle.dwHighDateTime << 32) | ftIdle.dwLowDateTime;
ULONGLONG uKrnl = ((ULONGLONG)ftKrnl.dwHighDateTime << 32) | ftKrnl.dwLowDateTime;
ULONGLONG uUsr = ((ULONGLONG)ftUsr.dwHighDateTime << 32) | ftUsr.dwLowDateTime;
if(bUsedOnce)
{
ULONGLONG uDiffIdle = uIdle - uOldIdle;
ULONGLONG uDiffKrnl = uKrnl - uOldKrnl;
ULONGLONG uDiffUsr = uUsr - uOldUsr;
if(uDiffKrnl + uDiffUsr)
{
//Calculate percentage
nRes = (int)((uDiffKrnl + uDiffUsr - uDiffIdle) * 100 / (uDiffKrnl + uDiffUsr));
}
}
bUsedOnce = TRUE;
uOldIdle = uIdle;
uOldKrnl = uKrnl;
uOldUsr = uUsr;
}
return nRes;
}
I tested it on several of my PCs and the code seems to return reliable results. Unfortunately, on one machine the code above seems to produce results 20% lower than the reading from the Task Manager (namely, the task manager would be showing 100% CPU utilization and my code would consistently return only 80%.)
CPU specifics on that machine:
Intel(R) Core(TM) i7
Cores: 4
Logical CPUs: 8
NUMA nodes: 1
Does anyone have any idea why this code could get such faulty reading?
EDIT: PS. It turns out that the CPU that produces this incorrect result is overclocked.