How is CPU usage calculated?

后端 未结 8 1607
故里飘歌
故里飘歌 2020-12-12 13:43

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

相关标签:
8条回答
  • 2020-12-12 14:25

    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.

    0 讨论(0)
  • 2020-12-12 14:25

    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.

    0 讨论(0)
提交回复
热议问题