On my desktop, I have a little widget that tells me my current CPU usage. It also shows the usage for each of my two cores.
I always wondered, how does the CPU calc
To get CPU usage, periodically sample the total process time, and find the difference.
For example, if these are the CPU times for process 1:
kernel: 1:00:00.0000
user: 9:00:00.0000
And then you obtain them again two seconds later, and they are:
kernel: 1:00:00.0300
user: 9:00:00.6100
You subtract the kernel times (for a difference of 0.03
) and the user times (0.61
), add them together (0.64
), and divide by the sample time of 2 seconds (0.32
).
So over the past two seconds, the process used an average of 32% CPU time.
The specific system calls needed to get this info are (obviously) different on every platform. On Windows, you can use GetProcessTimes, or GetSystemTimes if you want a shortcut to total used or idle CPU time.
Well, as far as I understand it there's a giant
while(true){}
loop that the operating systems spins up. Your process is managed from within that loop. It allows external code to be executed directly on the processor in chunks. Without exaggerating too much, this is an uber-simplification of what is actually going on.