1

How to get the cpu usage? I found some piece of code from google, but they are not very accurate, maybe I used them in the wrong way.

Here's my code:

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

a sample output:

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

It does the same thing in each loop, why the output is different.

aj3423
  • 2,003
  • 3
  • 32
  • 70
  • 1
    This sort of measurement of CPU usage is never accurate, it can´t be. – deviantfan Jun 02 '15 at 10:31
  • The resolution of GetProcessTimes() is no better than the system clock interrupt rate, 15.625 msec by default. You must use QueryPerformanceCounter() to get a high resolution measurement. – Hans Passant Jun 02 '15 at 11:01
  • Do you use compiler optimizations? Your `do_expensive_calculation` has no side effects and `void` return. The compiler may optimize it away completely. – 463035818_is_not_an_ai Jun 02 '15 at 11:42

0 Answers0