I was wondering how to calculate the total CPU usage of a process.
If I do cat /proc/pid/stat
, I think the relevant fields are (taken from lindevdoc.org):
- CPU time spent in user code, measured in jiffies
- CPU time spent in kernel code, measured in jiffies
- CPU time spent in user code, including time from children
- CPU time spent in kernel code, including time from children
So is the total time spend the sum of fields 14 to 17?
Here is another way that I got my App's CPU usage. I did this in Android, and it makes a kernel top call and gets the CPU usage for your apps PID using what top returns.
Yes, you can say so. You can convert those values into seconds using formula:
HZ value is configurable - done at kernel configuration time.
If need to calculate how much cpu% used by a process in last 10 secs
--delay of 10 secs
total_time (13+14) in jiffies => t2 starttime(22) in jiffies => s2
t2-t1 *100 / s2 - s1 wouldnt give the % ??
Preparation
To calculate CPU usage for a specific process you'll need the following:
/proc/uptime
#1
uptime of the system (seconds)/proc/[PID]/stat
#14
utime
- CPU time spent in user code, measured in clock ticks#15
stime
- CPU time spent in kernel code, measured in clock ticks#16
cutime
- Waited-for children's CPU time spent in user code (in clock ticks)#17
cstime
- Waited-for children's CPU time spent in kernel code (in clock ticks)#22
starttime
- Time when the process started, measured in clock ticksgetconf CLK_TCK
can be used to return the number of clock ticks.sysconf(_SC_CLK_TCK)
C function call may also be used to return the hertz value.Calculation
First we determine the total time spent for the process:
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
:Next we get the total elapsed time in seconds since the process started:
Finally we calculate the CPU usage percentage:
See also
Here's what you're looking for:
This code is actually from cpulimit, but uses openssl snippets.