MSDN Forum: cpu usage caculated by windows API is not same as the value in task manager

Li, Cindy 1 Reputation point
2020-08-18T11:47:14.933+00:00

below is my code, but the cpu usage caculated by the code is not the same as the value in task manager.
Could someone tell me where is wrong, thanks?

include <iostream>

include <Windows.h>

static bool getSystemCPUTime(ULONGLONG &totalTime, ULONGLONG &idleTime)
{
FILETIME ftSysIdle, ftSysKernel, ftSysUser;

if (!GetSystemTimes(&ftSysIdle, &ftSysKernel, &ftSysUser))
{
    return false;
}

ULARGE_INTEGER sysKernel, sysUser, sysIdle;
sysKernel.HighPart = ftSysKernel.dwHighDateTime;
sysKernel.LowPart = ftSysKernel.dwLowDateTime;
sysUser.HighPart = ftSysUser.dwHighDateTime;
sysUser.LowPart = ftSysUser.dwLowDateTime;
sysIdle.HighPart = ftSysIdle.dwHighDateTime;
sysIdle.LowPart = ftSysIdle.dwLowDateTime;

totalTime = sysKernel.QuadPart + sysUser.QuadPart;
idleTime = sysIdle.QuadPart;

return true;

}
int main()
{
unsigned int interval = 1000;
ULONGLONG totalPrev = 0, totalCurr = 0;
ULONGLONG idlePrev = 0, idleCurr = 0;

unsigned int totalCPUUsage = 0;
int result = getSystemCPUTime(totalPrev, idlePrev);
printf("result =%d\n", result);
while (true)
{
    Sleep(interval);
    if (getSystemCPUTime(totalCurr, idleCurr))
    {
        LONGLONG total = totalCurr - totalPrev;
        if (total > 0)
        {
            LONGLONG idle = idleCurr - idlePrev;
            totalCPUUsage = static_cast<unsigned int>(100 * (total - idle) / (total));
            printf("totalCPUUsage is %d, idle is %I64u, total is %I64u\n", totalCPUUsage, idle, total);
        }
        totalPrev = totalCurr;
        idlePrev = idleCurr;
    }

}
}

Windows development Windows API - Win32
{count} votes

1 answer

Sort by: Most helpful
  1. Drake Wu - MSFT 996 Reputation points
    2020-08-20T06:38:41.257+00:00

    You could use the api of Performance Counters. Check the following sample,

    #include <windows.h>  
    #include <iostream>  
    #include <pdh.h>  
    #pragma comment(lib, "pdh.lib")  
      
    int main()  
    {  
        PDH_HQUERY cpuQuery;  
        PDH_HCOUNTER cpuTotal;  
        PdhOpenQuery(NULL, NULL, &cpuQuery);  
        PdhAddCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);  
        PdhCollectQueryData(cpuQuery);  
        DWORD time = 1000;  
        for(;;)  
        {  
            Sleep(time);  
            PDH_FMT_COUNTERVALUE counterVal;  
            PdhCollectQueryData(cpuQuery);  
            PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);  
            printf("%f\n", counterVal.doubleValue);  
        }  
        return 0;  
    }  
    

    Or refer to the sample on MSDN: Browsing Performance Counters

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.