How is CPU usage calculated?

后端 未结 8 1683
故里飘歌
故里飘歌 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:23

    One way to do it is as follows:

    Pick a sampling interval, say every 5 min (300 seconds) of real elapsed time. You can get this from gettimeofday.

    Get the process time you've used in that 300 seconds. You can use the times() call to get this. That would be the new_process_time - old_process_time, where old_process_time is the process time you saved from the last time interval.

    Your cpu percentage is then (process_time/elapsed_time)*100.0 You can set an alarm to signal you every 300 seconds to make these calculations.

    I have a process that I do not want to use more than a certain target cpu percentage. This method works pretty good, and agrees well with my system monitor. If we're using too much cpu, we usleep for a little.

提交回复
热议问题