How is CPU usage calculated?

后端 未结 8 1650
故里飘歌
故里飘歌 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.

提交回复
热议问题