c ++在Windows上获得准确的cpu使用率

时间:2015-06-02 10:27:57

标签: c++ windows cpu-usage

如何获取cpu使用情况?我从谷歌找到了一些代码,但它们不是很准确,也许我用错了方法。

这是我的代码:

#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);
    }
}

示例输出:

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

它在每个循环中都做同样的事情,为什么输出不同。

0 个答案:

没有答案