Is there a way to get CPU usage in CentOS? I need to parse this information and graph it from a Perl script, so it should preferably be a simple tool that prints out one singular output.
atop @ http://www.atoptool.nl/ Will write to a log file, etc. Details here: http://www.atoptool.nl/systemreports.php
even easier, look at /proc/loadavg
, it shows something like:
$ cat /proc/loadavg
0.37 0.67 0.68 1/312 8594
First three numbers are, "the number of cpu's you would need to handle the current load". Meaning that on multi core you can have a load of 5 without a problem. The three numbers are averaged over different intervals (1, 5 and 15 minutes, according to man uptime
)
I actually use /proc/stat for this.. here's the important bits of the python I use for my dzen2 widget.
while(1):
f = file("/proc/stat","r")
fcon = f.read().split("\n")[0].split()
new.user, unice, new.sys, new.idle, new.iowait = [
int(x) for x in fcon[1:6] ]
new.user += unice
master.user = new.user - old.user
master.sys = new.sys - old.sys
master.idle = new.idle - old.idle
master.iowait = new.iowait - old.iowait
maxval = master.user + master.sys + master.idle + master.iowait
curval = master.user + master.sys + master.iowait
old.copy(new)
print (float(curval)/maxval) * 100 )
time.sleep(1)
This prints a percentage use of the processor, by the second.
Wrong language, I know, but you should be able to get the gist of which columns of the output refer to what.
You can use top
in batch mode with 1 (or more) iterations. Then use grep
to parse through it.
$ top -b -n 1 | grep -2 "load average"
top - 12:08:31 up 14 days, 19:03, 26 users, load average: 0.25, 0.45, 0.37
Tasks: 219 total, 1 running, 217 sleeping, 0 stopped, 1 zombie
Cpu(s): 4.2%us, 0.6%sy, 0.0%ni, 94.0%id, 1.0%wa, 0.0%hi, 0.3%si, 0.0%st
or
$ top -b -n 1 | grep "Cpu(s)\:"
Cpu(s): 4.2%us, 0.6%sy, 0.0%ni, 94.0%id, 1.0%wa, 0.0%hi, 0.3%si, 0.0%st
Further, you use can use awk
to get a specific column and work from there.
$ top -b -n 1 | grep "Cpu(s)\:" | awk '{print $2}'
4.2%us,