-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpu-utilization.sh
executable file
·36 lines (28 loc) · 1.01 KB
/
cpu-utilization.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/env bash
# by Paul Colby (http://colby.id.au), no rights reserved ;)
# Modified to have no integer rounding by Green Coding Solutions, no rights reserved :)
PREV_TOTAL=0
PREV_IDLE=0
count=${1:--1}
while [[ $count -ne 0 ]]; do
CPU=($(sed -n 's/^cpu\s//p' /proc/stat))
IDLE=${CPU[3]} # Just the idle CPU time.
TIME_BEFORE=$(date +%s%N)
TOTAL=0
for VALUE in "${CPU[@]:0:8}"; do
TOTAL=$((TOTAL+VALUE))
done
sleep 1
TIME_AFTER=$(date +%s%N)
DIFF_IDLE=$((IDLE-PREV_IDLE))
DIFF_TOTAL=$((TOTAL-PREV_TOTAL))
DIFF_USAGE=$(echo "${DIFF_TOTAL} ${DIFF_IDLE} ${DIFF_TOTAL}" | awk '{printf "%.2f", (( 1000 * ($1 - $2) / $3) / 10) }')
DIFF_USAGE=$(echo $DIFF_USAGE | sed 's/^\./0&/')
echo $(echo "$TIME_AFTER $TIME_BEFORE" | awk '{printf "%.10f", ($1 - $2) / 1000000000 }') "$DIFF_USAGE"
# Remember the total and idle CPU times for the next check.
PREV_TOTAL="$TOTAL"
PREV_IDLE="$IDLE"
if [[ $count -ne -1 ]]; then
count=$((count - 1))
fi
done