Preparation
To calculate CPU usage for a specific process you’ll need the following:
/proc/uptime#1uptime of the system (seconds)
/proc/[PID]/stat#14utime– CPU time spent in user code, measured in clock ticks#15stime– CPU time spent in kernel code, measured in clock ticks#16cutime– Waited-for children’s CPU time spent in user code (in clock ticks)#17cstime– Waited-for children’s CPU time spent in kernel code (in clock ticks)#22starttime– Time when the process started, measured in clock ticks
- Hertz (number of clock ticks per second) of your system.
- In most cases,
getconf CLK_TCKcan be used to return the number of clock ticks. - The
sysconf(_SC_CLK_TCK)C function call may also be used to return the hertz value.
- In most cases,
Calculation
First we determine the total time spent for the process:
total_time = utime + stime
We also have to decide whether we want to include the time from children processes. If we do, then we add those values to total_time:
total_time = total_time + cutime + cstime
Next we get the total elapsed time in seconds since the process started:
seconds = uptime - (starttime / Hertz)
Finally we calculate the CPU usage percentage:
cpu_usage = 100 * ((total_time / Hertz) / seconds)
See also
Top and ps not showing the same cpu result
How to get total cpu usage in Linux (c++)
Calculating CPU usage of a process in Linux