如何获得每个cpu的利用率百分比?

时间:2017-11-14 16:32:31

标签: bash shell cpu-usage

我编写了一个脚本,根据我发现的给出平均利用率百分比的脚本来获取每个cpu的利用率百分比。我找到的脚本效果很好,百分比每秒都在变化。不幸的是,我写的脚本显示的百分比根本没有变化。你知道我做错了什么,或者你是否有更好的想法来获得每个cpu的利用率百分比?

修改

工作部分是“获得CPU的平均使用”部分,非工作部分是“获得所有CPUS之间的最大使用”

这是我的脚本,它显示了avg 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

1 个答案:

答案 0 :(得分:0)

我终于发现了我的问题,我在循环中初始化了我的数组,并且它需要在循环之外进行初始化。我设法使脚本工作,如果有人感兴趣,这是最后的脚本:

#!/bin/bash

# this function is used to get the infos about the cpu
getCpuScores() {
    CPU=(`cat /proc/stat | grep ^cpu$1`)
}

# this function is used to get the percentage of utilization of a cpu
getPercentageOfCpu() {
    unset CPU[0]
    local idle=${CPU[4]}
    local total=0
    for val in "${CPU[@]:0:4}"; do
        let "total=$total+$val"
    done

    let "diff_idle=$idle-${PREV_IDLES[$1]}"
    let "diff_total=$total-${PREV_TOTALS[$1]}"
    let "diff_usage=(1000*($diff_total-$diff_idle)/$diff_total+5)/10"

    PERCENTAGES[$1]=$diff_usage
    PREV_IDLES[$1]=$idle
    PREV_TOTALS[$1]=$total
}


# first we initialize all the needed variables
PREV_TOTAL=0
PREV_IDLE=0
# this is to get the number of cpu
CPUS=(`cat /proc/stat | grep '^cpu[0-9]'`)
lengthArray=${#CPUS[@]}
numberOfCpus=$((lengthArray/11))
i=0
PREV_TOTALS=()
PREV_IDLES=()
PERCENTAGES=()
# we instenciate the arrays and set their values to 0
while [ $i -lt $numberOfCpus ]; do
    PREV_TOTALS+=(0)
    PREV_IDLES+=(0)
    PERCENTAGES+=(0)
    i=$((i+1))
done

# MAIN LOOP

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
# ------------------------
  # first we get the percentage of utilization for each cpu
  i=0
  while [ $i -lt $numberOfCpus ]; do
    # we get the cpu score to be able to calculate the percentage of utilization
    getCpuScores $i
    # then we calculate the percentage of the cpu and put it in an array
    getPercentageOfCpu $i

    i=$((i+1))

  done

  # then we get the max
  MAX=${PERCENTAGES[0]}
  cpu=0
  i=0

  while [ $i -lt $numberOfCpus ]; do
    if [ ${PERCENTAGES[$i]} -gt $MAX ]; then
        MAX=${PERCENTAGES[$i]}
        cpu=$i
    fi
    i=$((i+1))
  done

  # finally we display the avg cpu usage and the max cpu usage
  echo -en "\rCPU: $DIFF_USAGE%  CPU$cpu: $MAX% \b\b"

  # Wait before checking again.
  sleep 1
done

该脚本显示平均CPU使用率的百分比以及最常用的cpu使用百分比。