Middle
How does top calculate CPU%? What algorithm does it use?
sobes.tech AI
Answer from AI
The top command in Linux shows the percentage of CPU usage for each process, calculated based on the time the process has spent in the running state (CPU time) over a certain interval.
The algorithm is roughly as follows:
topperiodically (usually once per second) reads process statistics from/proc/[pid]/stat.- For each process, it takes the total CPU time spent (user + system) and compares it with the previous measurement.
- The difference in CPU time for the process is divided by the difference in time between measurements (usually 1 second), which gives the CPU usage share of the process during that interval.
- The result is normalized to the number of available CPUs if necessary.
Simplified formula:
CPU% = (delta_process_cpu_time / delta_time) * 100
Where delta_process_cpu_time is the change in CPU time of the process between two measurements, and delta_time is the time between measurements (usually 1 second).
Thus, if a process used the CPU all the time between measurements, CPU% will be close to 100% on a single core. If the system is multi-core, the maximum value can be higher than 100% if the process uses multiple cores simultaneously.