Created
April 25, 2019 21:25
-
-
Save bwedding/0e5bffb5cd9ba59281d4ab3560d3901a to your computer and use it in GitHub Desktop.
CPU Load measurement for Windows, found on StackOverflow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Windows.h> | |
static float CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks) | |
{ | |
static unsigned long long _previousTotalTicks = 0; | |
static unsigned long long _previousIdleTicks = 0; | |
unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks; | |
unsigned long long idleTicksSinceLastTime = idleTicks-_previousIdleTicks; | |
float ret = 1.0f-((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0); | |
_previousTotalTicks = totalTicks; | |
_previousIdleTicks = idleTicks; | |
return ret; | |
} | |
static unsigned long long FileTimeToInt64(const FILETIME & ft) {return (((unsigned long long)(ft.dwHighDateTime))<<32)|((unsigned long long)ft.dwLowDateTime);} | |
// Returns 1.0f for "CPU fully pinned", 0.0f for "CPU idle", or somewhere in between | |
// You'll need to call this at regular intervals, since it measures the load between | |
// the previous call and the current one. Returns -1.0 on error. | |
float GetCPULoad() | |
{ | |
FILETIME idleTime, kernelTime, userTime; | |
return GetSystemTimes(&idleTime, &kernelTime, &userTime) ? CalculateCPULoad(FileTimeToInt64(idleTime), FileTimeToInt64(kernelTime)+FileTimeToInt64(userTime)) : -1.0f; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment