I want to programmatically [in C] calculate CPU usage % for a given process ID in Linux.
How can we get the realtime CPU usage % for a given process?
To make it further clear:
- I should be able to determine the CPU usage for the provided processid or process.
- The process need not be the child process.
- I want the solution in 'C' language.
You can read the manpage for proc for more detail, but in summary you can read /proc/[number]/stat to get the information about a process. This is also used by the 'ps' command.
All the fields and their scanf format specifiers are documented in the proc manpage.
Here are some of the information from the manpage copied (it is quite long):
You need to parse out the data from
/proc/<PID>/stat
. These are the first few fields (fromDocumentation/filesystems/proc.txt
in your kernel source):You're probably after
utime
and/orstime
. You'll also need to read thecpu
line from/proc/stat
, which looks like:This tells you the cumulative CPU time that's been used in various categories, in units of jiffies. You need to take the sum of the values on this line to get a
time_total
measure.Read both
utime
andstime
for the process you're interested in, and readtime_total
from/proc/stat
. Then sleep for a second or so, and read them all again. You can now calculate the CPU usage of the process over the sampling time, with:Make sense?
Instead of parsing this from proc, one can use functions like getrusage() or clock_gettime() and calculate the cpu usage as a ratio or wallclock time and time the process/thread used on the cpu.
I wrote two little C function based on cafs answer to calculate the user+kernel cpu usage of of an process: https://github.com/fho/code_snippets/blob/master/c/getusage.c
When you want monitor specified process, usually it is done by scripting. Here is perl example. This put percents as the same way as top, scalling it to one CPU. Then when some process is active working with 2 threads, cpu usage can be more than 100%. Specially look how cpu cores are counted :D then let me show my example:
I hope it will help you in any monitoring. Of course you should use scanf or other C functions for converting any perl regexpes I've used to C source. Of course 1 second for sleeping is not mandatory. you can use any time. effect is, you will get averrage load on specfied time period. When you will use it for monitoring, of course last values you should put outside. It is needed, because monitoring usually calls scripts periodically, and script should finish his work asap.