获取当前CPU利用率的方法在Windows 10上无法可靠地运行

时间:2017-02-07 22:04:49

标签: c++ windows winapi windows-10 cpu-usage

我一直在使用以下方法获取整个计算机的当前CPU利用率:

HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);

//Use a simple infinite loop to display the concept
for(;; ::Sleep(500))
{
    COORD coord = {0, 0};
    SetConsoleCursorPosition(hOut, coord);

    int nCpuUse = get_cpu_utilization_method_01();

    _tprintf(L"CPU Usage: %d\t", nCpuUse);
}


int get_cpu_utilization_method_01()
{
    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;

        //Only if we have previous values
        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));

                //Check value and correct it (Just in case)
                if(nRes < 0)
                    nRes = 0;
                else if(nRes > 100)
                    nRes = 100;
            }
        }

        //Remember previous data
        bUsedOnce = TRUE;
        uOldIdle = uIdle;
        uOldKrnl = uKrnl;
        uOldUsr = uUsr;
    }

    return nRes;

}

但是,自从Windows 10我收到软件用户的报告后,这种方法提供的读数可能是错误的。有些人告诉我,它可以报告的值低至Windows Task Manager显示的一半。

我已经运行了一段时间的测试,它似乎与我的笔记本电脑上Task Manager的读数有点接近,但当我在桌面上使用Intel Core i7-4770 CPU运行它时@ 3.40GHz,4个物理核心和8个逻辑核心,读数似乎一直太低:

enter image description here

请注意,我在相同的硬件上安装了Windows 7(现在运行的是Windows 10),然后在Windows 7上运行得非常可靠。

那么任何想法如何让它在Windows 10下运行?

1 个答案:

答案 0 :(得分:2)

试试这个:

#include "TCHAR.h"
#include "pdh.h"

static PDH_HQUERY cpuQuery;
static PDH_HCOUNTER cpuTotal;

void init(){
PdhOpenQuery(NULL, NULL, &cpuQuery);
PdhAddCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
PdhCollectQueryData(cpuQuery);
}

double getCurrentValue(){
PDH_FMT_COUNTERVALUE counterVal;

PdhCollectQueryData(cpuQuery);
PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
return counterVal.doubleValue;
}