tags:

views:

4303

answers:

5

Hi

I want to programatically [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.
A: 

what about catching (grep-ing) output of top.

dusoft
Thats really not a best way to do efficient;y
codingfreak
Will probably require an "expensive" system call to start 'top'.
Liran Orevi
@Liran: Rightly said :)
Aviator
Forget about this way of doing things .... in C
codingfreak
+4  A: 

getrusage() can help you in determining the usage of current process or its child

Update: I can't remember an API. But all details will be in /proc/PID/stat, so if we could parse it, we can get the percentage.

EDIT: Since CPU % is not straight forward to calculate, You could use sampling kind of stuff here. Read ctime and utime for a PID at a point in time and read the same values again after 1 sec. Find the difference and divide by hundred. You will get utilization for that process for past one second.

(might get more complex if there are many processors)

Aviator
How does getrusage() system call help me in calculating CPU usage of a process ??
codingfreak
@codingfreak. i misunderstood the question. Now after u updated it, clear.
Aviator
@AviatorCPU % = (processusertime + processkerneltime)/(CPUusertime+CPUkerneltime)How can I get the values for "processusertime" and so on. ???I see different values down in "/proc/PID/stat" file. So which one corresponds to which value ??
codingfreak
@codingfreak:CPU time is difficult to calculate. U need to loop through all PID stats i guess (though not sure)
Aviator
@Aviator there would be some way or other to do it ... since even applications like top should calculate the CPU usage to show in their output
codingfreak
@codingfreak: Yes. There should be. I think they all will be using /proc/PIDs/stat internally. I can think of no other place they can get so much data!
Aviator
+1  A: 

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):

          pid %d The process ID.

          comm %s
                 The  filename of the executable, in parentheses.  This is
                 visible whether or not the executable is swapped out.

          state %c
                 One character from the string "RSDZTW" where  R  is  runâ
                 ning,  S is sleeping in an interruptible wait, D is waitâ
                 ing in uninterruptible disk sleep,  Z  is  zombie,  T  is
                 traced or stopped (on a signal), and W is paging.

          ppid %d
                 The PID of the parent.

          pgrp %d
                 The process group ID of the process.

          session %d
                 The session ID of the process.

          tty_nr %d
                 The tty the process uses.

          tpgid %d
                 The  process group ID of the process which currently owns
                 the tty that the process is connected to.
Andre Miller
@Andre Miller - Where does it show CPU usage % ???
codingfreak
“CPU usage” and “current state” are like location and velocity. If you know one you can’t know the other. CPU usage depends on a duration so you have to check yourself how often your process is in the “R” state.
Bombe
Hmm, good question, I always just assumed it would be there! Presumably you should be able to calculate it from these variables
Andre Miller
If you check the output of top command you can see CPU usage .... but I am not intrested in greping through top output to calculate CPU usage .....
codingfreak
@codingfreak: `ps aux` is better :)
Aviator
@Aviator - I have already told u to forget about grepping the output of a shell command to determine the CPU USAGE %
codingfreak
@codingfreak : :) I understand. Just told! :)
Aviator
You could always go check the source code of top to see how they did it. I'm guessing they also look at /proc/<pid>/stat and use a a calculation to find the utilization over time.
Andre Miller
A: 

Take a look at the "pidstat" command, sounds like exactly what you require.

James Anderson
@James - I am not able to access pidstat command in my FEDORA 9 machine.
codingfreak
@codingfreak - you need to install Sysstat tool for it
Chintan
+4  A: 

You need to parse out the data from /proc/<PID>/stat. These are the first few fields (from Documentation/filesystems/proc.txt in your kernel source):

Table 1-3: Contents of the stat files (as of 2.6.22-rc3)
..............................................................................
 Field          Content
  pid           process id
  tcomm         filename of the executable
  state         state (R is running, S is sleeping, D is sleeping in an
                uninterruptible wait, Z is zombie, T is traced or stopped)
  ppid          process id of the parent process
  pgrp          pgrp of the process
  sid           session id
  tty_nr        tty the process uses
  tty_pgrp      pgrp of the tty
  flags         task flags
  min_flt       number of minor faults
  cmin_flt      number of minor faults with child's
  maj_flt       number of major faults
  cmaj_flt      number of major faults with child's
  utime         user mode jiffies
  stime         kernel mode jiffies
  cutime        user mode jiffies with child's
  cstime        kernel mode jiffies with child's

You're probably after utime and/or stime. You'll also need to read the cpu line from /proc/stat, which looks like:

cpu  192369 7119 480152 122044337 14142 9937 26747 0 0

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 and stime for the process you're interested in, and read time_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:

user_util = 100 * (utime_after - utime_before) / (time_total_after - time_total_before);
sys_util = 100 * (stime_after - stime_before) / (time_total_after - time_total_before);

Make sense?

caf
@caf - I am really a newbie to this jiffy stuff ... sorry not able to understand what your saying ....
codingfreak
A "jiffy" is a unit of CPU time. Exactly what it corresponds to in wall-clock time depends on the architecture and how your kernel is configured, but the important thing is that `/proc/stat` tells you how many jiffies the CPU has executed in total, and `/proc/<PID>/stat` tells you how many jiffies have been executed by a single process.
caf
@caf - I am trying to learn the jiffy stuff .. meanwhile can you write down small code where u calculate the CPU usage of a process ??
codingfreak
@codingfreak - As caf says, you do not need to learn what jiffy really is, just follow the given formula.
eyazici