【发布时间】:2017-11-15 04:14:56
【问题描述】:
我编写了一个脚本,根据我发现的给出平均利用率百分比的脚本来获取每个 cpu 的利用率百分比。我发现的脚本效果很好,百分比每秒都在变化。不幸的是,我编写的脚本显示的百分比根本没有改变。您是否知道我做错了什么,或者您是否有更好的想法来获取每个 cpu 的利用率百分比?
编辑
工作部分是“获取 CPU 的平均使用率”部分,非工作部分是“获取所有 CPU 之间的最大使用率”
这是我的脚本,它显示了平均 cpu 使用率和使用最多的 cpu:
#!/bin/bash
PREV_TOTAL=0
PREV_IDLE=0
while true; do
# GET THE MEAN USAGE OF THE CPU
# -----------------------------
# we get the mean of the cpu usage
CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
unset CPU[0] # Discard the "cpu" prefix.
IDLE=${CPU[4]}
# Calculate the total CPU time.
TOTAL=0
for VALUE in "${CPU[@]:0:4}"; 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"
# Remember the total and idle CPU times for the next check.
PREV_TOTAL="$TOTAL"
PREV_IDLE="$IDLE"
# GET THE MAX USAGE BETWEEN ALL THE CPUS
# --------------------------------------
# here we get an array with all the cpus
CPUS=(`cat /proc/stat | grep '^cpu[0-9]'`)
lengthArray=${#CPUS[@]}
numberOfCpus=$((lengthArray/11))
i=0
numberOfCpus=$((lengthArray/11))
TOTALS=()
IDLES=()
PERCENTAGES=()
PREV_TOTALS=()
PREV_IDLES=()
# we instenciate the arrays and set their values to 0
while [ $i -lt $numberOfCpus ]; do
TOTALS+=(0)
IDLES+=(0)
PERCENTAGES+=(0)
PREV_TOTALS+=(0)
PREV_IDLES+=(0)
i=$((i+1))
done
i=0
index=1
limit=$((index+4))
# we loop through the array to get each total for each cpu
while [ $i -lt $numberOfCpus ]; do
IDLES[$i]=${CPUS[$index+3]}
# since we only want the first four numbers for each cpu, we have to loop in a strange way
while [ $index -lt $limit ]; do
TOTALS[$i]=$((TOTALS[$i]+CPUS[$index]))
index=$((index+1))
done
# 7 is the number of array element before the next series of number that we want
index=$((limit+7))
# we set the limit to four+the index because we only want the four numbers after the index
limit=$((index+4))
i=$((i+1))
done
# now we calculate the percentage of usage for every cpu so we can get the max percentage
i=0
# we calculate the percentage for each cpu
while [ $i -lt $numberOfCpus ]; do
let "DIFF_IDLE_i=${IDLES[$i]}-${PREV_IDLES[$i]}"
let "DIFF_TOTAL_i=${TOTALS[$i]}-${PREV_TOTALS[$i]}"
let "DIFF_USAGE_i=(1000*($DIFF_TOTAL_i-$DIFF_IDLE_i)/$DIFF_TOTAL_i+5)/10"
PERCENTAGES[$i]=$DIFF_USAGE_i
PREV_TOTALS[$i]=${TOTALS[$i]}
PREV_IDLES[$i]=${IDLES[$i]}
i=$((i+1))
done
MAX=${PERCENTAGES[0]}
cpu=0
i=0
# here we look for the max
for percent in ${PERCENTAGES[@]}; do
if [ $percent -gt $MAX ]; then
cpu=$i
MAX=$percent
fi
i=$((i+1))
done
echo -en "\rCPU: $DIFF_USAGE% CPU$cpu: $MAX% \b\b"
# Wait before checking again.
sleep 1
done
【问题讨论】: