[lug] Determining CPU usage

Zan Lynx zlynx at acm.org
Thu May 1 12:11:42 MDT 2008


On Thu, 2008-05-01 at 10:25 -0600, Jim Buzbee wrote:
> I'm trying to write a script that periodically looks at a bunch of
> processes and reports, among other things,  roughly the amount of CPU
> being currently consumed by each process.  It works, but it's not very
> efficient.
> 
> Maybe there is something in /proc that would help?
> 
> Below is some psuedo bash code that does the job fairly poorly.
> 
> Anyone have a better method?

A better faster way is to use the /proc/[pid]/stat file yourself.  Read
it in C using scanf: it is designed to be easy to work with that way.
You can look up the field definitions in the Linux kernel Documentation
directory, I think, or look at the kernel fs/proc source.

To get the value you want, you'd add up the user, system and nice used
time and store it, get the total run time and store it, then wait 1
second and do it again.  Find the differences and calculate your 1
second CPU% usage.

You could also do this in Perl, Python, Ruby or whatever...Even shell
can do it with something like read x y z i j k < /proc/1/stat.

Remember: for speed never use separate commands.  The kernel, dynamic
linker and the program have to do a rather amazing amount of work every
time you ask it to launch another "ps" command.
-- 
Zan Lynx <zlynx at acm.org>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20080501/bb004d91/attachment.pgp>


More information about the LUG mailing list