[lug] Determining CPU usage
Jim Buzbee
jbuzbee at nyx.net
Thu May 1 10:25:24 MDT 2008
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?
for pid in BLAH BLAH BLAH
...
# test the validity of the pid (doesn't harm a running process )
kill -0 $pid >/dev/null 2>&1
# if it's alive
if [ $? -eq 0 ]
then
# I think this gives me the % time on CPU vs sleeping
# this is pretty fast, but it's not really what I want
cpu=`ps -p $pid -o pcpu --no-headers`
# I think this give me the % of CPU being currently used
# which is what I want, but calculating it is inefficient
cpu=`top -p $pid -b -n 1 | grep " $pid " | awk '{print $9}'`
# is there a better way?
...
--------------------------------------------------------------------------------
Jim Buzbee "I was gratified to be able to
jbuzbee at nyx.net answer promptly, and I did. I
http://batbox.org said I didn't know." Mark Twain
More information about the LUG
mailing list