title: Get CPU usage in shell script?
body: <p>I'm running some <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">JMeter</a> 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.</p>
  
  <p>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 <code>ps</code> like this:</p>
  
  <pre><code>PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`
  </code></pre>
  
  <p>...running the command every X seconds and appending the results to a text file. (for anyone wondering, <code>pmem</code> = % mem usage and <code>nlwp</code> is number of threads)</p>
  
  <p>However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, <code>pcpu</code> is defined as:</p>
  
  <blockquote>
    <p>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. </p>
  </blockquote>
  
  <p>In other words, <code>pcpu</code> gives me the % CPU utilization for the process for the <em>lifetime</em> of the process.</p>
  
  <p>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 <code>top</code> would give me
  (CPU utilization of the process since the last update). </p>
  
  <p>How can I collect this from within a shell script? </p>