Running Debian/Lenny - Linux 2.6.24-1-686 i686 GNU/Linux
/proc/[pid]/stat has the total cpu usage of a process, along with various other data.You can find the print statement in the source near the end of this file:
[linux_src]/linux-2.6.24/fs/proc/array.c :: static int do_task_stat([...])For example, if you determine the pid of firefox to be 3428
I ran
watch "cat /proc/3428/stat | sed 's/ /\n/g'" and just lined up the values with their c-variable names.
cputime_to_clock_t(utime), --> user time
cputime_to_clock_t(stime), --> system time
cputime_to_clock_t(cutime), --> child process user time
cputime_to_clock_t(cstime), --> child process system time
A little bit of counting, and we can retrieve these values via
cat /proc/[pid]/stat | cut -d " " -f 14-17For my firefox process, this command gave me numbers like:
4627014 49642 891 91And to close it out, a little psuedo-code (python, rather) to collect the information, given a pid file from /var/run, easily modified to use an exact, or feed in from command line, etc.
#!/usr/bin/python
import subprocess
import time
class CPUData():
pid = "`cat /var/run/pidfile.pid`" # pid from file
# pid = 1234 # static pid
delay = 1
def reap(self):
command = 'cat /proc/`cat %s`/stat | cut -d " " -f 14-17' % self.noxpid
# eg result: 4627014 49642 891 91
# utime stime cu cs
usage = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
pcpu = sum([int(v) for v in usage.stdout.read().split()])
return pcpu
def harvest(self):
v1,t1 = self.reap(),time.time()
time.sleep(self.delay)
v2,t2 = self.reap(),time.time()
return (v2-v1)/(t2-t1)
if __name__ == '__main__':
x = CPUData()
print "% CPU Usage:", x.harvest()
Sorry for the parsimonious nature of the post, first draft got wiped, should be some errors hiding somewhere (unsolicited exercise for the reader?)
)******