http://colby.id.au/node/39

Calculating CPU Usage from /proc/stat

I recently came across a number of forum topics asking how to calculate CPU usage from /proc/stat, which raised a very slight sense of challenge within me (was just in "the mood" to do some BASH scripting)... so, here's an example showing how to calculate CPU usage with a simple BASH script.

#!/bin/bash
# by Paul Colby (http://colby.id.au), no rights reserved ;)

PREV_TOTAL=0
PREV_IDLE=0

while true; do
  CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  unset CPU[0]                          # Discard the "cpu" prefix.
  IDLE=${CPU[4]}                        # Get the idle CPU time.

  # Calculate the total CPU time.
  TOTAL=0
  for VALUE in "${c...@]}"; do
    let "TOTAL=$TOTAL+$VALUE"
  done

  # Calculate the CPU usage since we last checked.
  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
  echo -en "\rCPU: $DIFF_USAGE%  \b\b"

  # Remember the total and idle CPU times for the next check.
  PREV_TOTAL="$TOTAL"
  PREV_IDLE="$IDLE"

  # Wait before checking again.
  sleep 1
done

The script should be pretty self-explanatory. It loops forever (just hit Ctrl-C when you want it to stop). Each time through the loop, it calculates the CPU usage by subtracting the CPU's "idle" time from the CPU's "total" time. Notice the way the percentage is calculated by multiplying by 1000, and then dividing by 10 at the end, instead of the "normal" approach of multiplying by 100. This is actually a cunning way of rounding off :) See the way I add 5 just before the divide by 10? So, for example, if the percentage was 45.6% then BASH would truncate the result to 45%. But, by multiplying by 1000 (instead of 100), and adding 5, the result is 461 (ie 456+5), which, when divided by 10 at the end, yields the correctly rounded result of 46% :) The other neat trick in the above script is the output "echo" statement:

echo -en "\rCPU: $DIFF_USAGE%  \b\b"

This causes the script to output the CPU % on just one line - ie continually overwriting the previous value. It works like this:

  • the "-e" parameter causes the "echo" command to interpret the "\r" and "\b" escape codes;
  • the "-n" parameter prevents the "echo" command from appending the usual carriage-return to the end of the line;
  • the two spaces after the "%" sign are there to overwrite previous characters that would be left over when going from double (or triple) digits down to single (or double) digits;
  • and finally, the two "\b" (backspace) codes put the cursor back to being immediately after the "%" symbol, otherwise the the two spaces above kinda leave the cursor hanging in the middle of nowhere.

Well, that's it. Any questions, or suggestions, add a comment below :)

Technorati Tags:Technorati Tags: BASH Linux

Trackback URL for this post:

CPU check plugin for Nagios

I’ve just finished version 1.0 of a CPU check plugin which is sh-compliant (as always) and calculates utilization through Jiffies rather than using another third party tool like iostat or top. This means it should work on all Linux machines right...

Interesting...

I just saw that my example script above has been extended in this forum post... nice to see it helping someone - even if only for discussion ;)

That's pretty cool, too bad

That's pretty cool, too bad he didn't link back to you. :-(

Oh well... Still nice to see someone utilizing it... and your name is still in there!!!

Nice

That was a good little read. (Somewhat useful too!)

I was wondering about the rounding and was going to ask; why don't you use higher percision (like 45.6%)?


Reply via email to