I am trying to get the CPU load and wish for as close result as possible to what is shown in Task Manager.
I first tried using WMI which returns a good result but is extremely slow (1-10 seconds to complete.
I am now trying to use GetSystemTimes
based on the code here
Here is the code:
static class ProcessorLogic {
// calc cpu
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetSystemTimes(out FILETIME lpIdleTime, out FILETIME lpKernelTime, out FILETIME lpUserTime);
static bool bUsedOnce = false;
static ulong uOldIdle = 0;
static ulong uOldKrnl = 0;
static ulong uOldUsr = 0;
public static int CPUusagePercent() {
int nRes = -1;
if (GetSystemTimes(out FILETIME ftIdle, out FILETIME ftKrnl, out FILETIME ftUsr)) {
ulong uIdle = ((ulong)ftIdle.dwHighDateTime << 32) | (uint)ftIdle.dwLowDateTime;
ulong uKrnl = ((ulong)ftKrnl.dwHighDateTime << 32) | (uint)ftKrnl.dwLowDateTime;
ulong uUsr = ((ulong)ftUsr.dwHighDateTime << 32) | (uint)ftUsr.dwLowDateTime;
if (bUsedOnce) {
ulong uDiffIdle = uIdle - uOldIdle;
ulong uDiffKrnl = uKrnl - uOldKrnl;
ulong uDiffUsr = uUsr - uOldUsr;
if ((uDiffKrnl + uDiffUsr) != 0) { //Calculate percentage
nRes = (int)((uDiffKrnl + uDiffUsr - uDiffIdle) * 100 / (uDiffKrnl + uDiffUsr));
}
}
bUsedOnce = true;
uOldIdle = uIdle;
uOldKrnl = uKrnl;
uOldUsr = uUsr;
}
return nRes;
}
}
The result I get are about 40% of what is shown on Task Manager (running on Intel(R) Core(TM) i7-10850H 2.70GHz 6 cores)
What am I doing wrong ?
I feel that I am reinventing the wheel here, is there a solid library/project/code to get these results correctly ?