Skip to content

Instantly share code, notes, and snippets.

@stoyanovgeorge
Created August 21, 2019 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stoyanovgeorge/6060bf115fb95a09db8822b255e9b2b3 to your computer and use it in GitHub Desktop.
Save stoyanovgeorge/6060bf115fb95a09db8822b255e9b2b3 to your computer and use it in GitHub Desktop.
Print the total CPU usage in the terminal and updates its value every second.
#!/bin/bash
# Created by Paul Colby (http://colby.id.au)
# Further edited by Georgi Stoyanov (http://gstoyanov.com), no rights reserved ;)
PREV_TOTAL=0
PREV_IDLE=0
# Determinining the number of CPU cores
CPU_CORES=$(nproc --all)
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
(( "TOTAL=$TOTAL+$VALUE" ))
done
# Calculate the CPU usage since we last checked.
(( "DIFF_IDLE=$IDLE-$PREV_IDLE" ))
(( "DIFF_TOTAL=$TOTAL-$PREV_TOTAL" ))
(( "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