Skip to content

Instantly share code, notes, and snippets.

@peerasan
Created June 8, 2019 14:29
Show Gist options
  • Select an option

  • Save peerasan/3371413b8c2c9285beeffbd813472182 to your computer and use it in GitHub Desktop.

Select an option

Save peerasan/3371413b8c2c9285beeffbd813472182 to your computer and use it in GitHub Desktop.
Linux CPU Usage
#!/bin/bash
# by Paul Colby (http://colby.id.au), no rights reserved ;)
# https://github.com/pcolby/scripts/blob/master/cpu.sh
PREV_TOTAL=0
PREV_IDLE=0
while true; do
# Get the total CPU statistics, discarding the 'cpu ' prefix.
CPU=(`sed -n 's/^cpu\s//p' /proc/stat`)
IDLE=${CPU[3]} # Just the idle CPU time.
# Calculate the total CPU time.
TOTAL=0
for VALUE in "${CPU[@]}"; 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment