Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get CPU usage in shell script?

I'm running some JMeter tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap.

I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using ps like this:

PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`

...running the command every X seconds and appending the results to a text file. (for anyone wondering, pmem = % mem usage and nlwp is number of threads)

However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, pcpu is defined as:

cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage.

In other words, pcpu gives me the % CPU utilization for the process for the lifetime of the process.

Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what top would give me (CPU utilization of the process since the last update).

How can I collect this from within a shell script?

like image 731
matt b Avatar asked Sep 08 '08 18:09

matt b


3 Answers

Use top -b (and other switches if you want different outputs). It will just dump to stdout instead of jumping into a curses window.

like image 153
Ben Collins Avatar answered Oct 27 '22 14:10

Ben Collins


The most useful tool I've found for monitoring a server while performing a test such as JMeter on it is dstat. It not only gives you a range of stats from the server, it outputs to csv for easy import into a spreadsheet and lets you extend the tool with modules written in Python.

like image 24
Tim Avatar answered Oct 27 '22 13:10

Tim


User load: top -b -n 2 |grep Cpu |tail -n 1 |awk '{print $2}' |sed 's/.[^.]*$//' System load: top -b -n 2 |grep Cpu |tail -n 1 |awk '{print $3}' |sed 's/.[^.]*$//' Idle load: top -b -n 1 |grep Cpu |tail -n 1 |awk '{print $5}' |sed 's/.[^.]*$//'

Every outcome is a round decimal.

like image 29
Bilzard Avatar answered Oct 27 '22 13:10

Bilzard