Created
November 21, 2024 06:26
-
-
Save fbakhda/b670be6650eb892eab4745f76e99056b to your computer and use it in GitHub Desktop.
Snapshot 5 datapoints of CPU Utilization percentage and print the 5th data point for CPU Utilization percentage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# by Paul Colby (http://colby.id.au), no rights reserved ;) | |
# modified by Bakhda, Firesh | |
PREV_TOTAL=0 | |
PREV_IDLE=0 | |
for INDEX in 1 2 3 4 5; do | |
# Get the total CPU statistics, discarding the 'cpu ' prefix. | |
CPU=$(sed -n 's/^cpu\s//p' /proc/stat) | |
set -- $CPU | |
IDLE=$(echo "$CPU" | tr -s " " | cut -d " " -f5) | |
for item in "$@" | |
do | |
TOTAL=$((TOTAL+item)) | |
done | |
# Empty out the array for next iteration | |
set -- | |
#echo "CPU: "$CPU | |
#echo "IDLE: "$IDLE | |
#echo "TOTAL: "$TOTAL | |
# 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 "DIFF_TOTAL: "$DIFF_TOTAL | |
#echo "DIFF_IDLE: "$DIFF_IDLE | |
#echo "DIFF_USAGE: "$DIFF_USAGE | |
c=$(echo "$DIFF_TOTAL $DIFF_IDLE" | awk '{printf("%.2f\n",(1000*($1-$2)/$1+5)/10)}') | |
USAGE="$USAGE $c" | |
# Debug | |
#echo "$USAGE" | |
# Remember the total and idle CPU times for the next check. | |
PREV_TOTAL="$TOTAL" | |
PREV_IDLE="$IDLE" | |
TOTAL="" | |
#echo "PREV_TOTAL: "$PREV_TOTAL | |
#echo "PREV_IDLE: "$PREV_IDLE | |
# Wait before checking again. | |
#echo "" | |
sleep 1 | |
done | |
set -- $USAGE | |
#echo "USAGE: "$USAGE | |
echo "$5" | awk '{ | |
if ($1 < 0) | |
printf("A %.2f",0); | |
else if ($1 > 100) | |
printf("B %.2f",100); | |
else | |
printf("C %.2f",$1); | |
}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment