Advertisement
ajcorrea

CPU Stats

Jun 4th, 2013
686
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2. # by Paul Colby (http://colby.id.au), no rights reserved ;)
  3.  
  4. PREV_TOTAL=0
  5. PREV_IDLE=0
  6.  
  7. while true; do
  8.   CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  9.   unset CPU[0]                          # Discard the "cpu" prefix.
  10.   IDLE=${CPU[4]}                        # Get the idle CPU time.
  11.  
  12.   # Calculate the total CPU time.
  13.   TOTAL=0
  14.   for VALUE in "${CPU[@]}"; do
  15.     let "TOTAL=$TOTAL+$VALUE"
  16.   done
  17.  
  18.   # Calculate the CPU usage since we last checked.
  19.   let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  20.   let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  21.   let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
  22.   echo -en "\rCPU: $DIFF_USAGE%  \b\b"
  23.  
  24.   # Remember the total and idle CPU times for the next check.
  25.   PREV_TOTAL="$TOTAL"
  26.   PREV_IDLE="$IDLE"
  27.  
  28.   # Wait before checking again.
  29.   sleep 1
  30. done
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement