CPU利用率統計-shell

來源:互聯網
上載者:User

 好久沒寫指令碼了,都開始忘記了,今天嘗試著寫了下,好多東西都要現查了,以後會每天寫點,簡單或者難的,有技術的沒技術的,總之,這東西多練習才好。

今天寫的這個指令碼先放這,一點點完善.

 

#!/usr/bin/env bash

PROC_FILE="/proc/stat"

function getline {
  #Original data, it looks like "cpu  391560 66418 112967 3144467 53328 10123 1642 0 0"
  local data=`cat $PROC_FILE | head -n 1`
  CUSER=`echo $data | awk '{print $2}'`
  CNICE=`echo $data | awk '{print $3}'`
  CSYSM=`echo $data | awk '{print $4}'`
  CIDLE=`echo $data | awk '{print $5}'`
  CIOW=`echo $data | awk '{print $6}'`
  CIRQ=`echo $data | awk '{print $7}'`
  CSIRQE=`echo $data | awk '{print $8}'`
  CSTEAL=`echo $data | awk '{print $9}'`
  CGUEST=`echo $data | awk '{print $10}'`

  CSUM=`expr $CUSER + $CNICE + $CSYSM + $CIDLE + $CIOW + $CIRQ + $CSIRQE + $SCTEAL + $CGUEST`
}

function calculate {
  #This is the sleep time between each getline invoke
  local delay=1
  if [ -n "$1" ] ; then
    delay=$1
  fi

  getline

  C_USER=$CUSER
  C_NICE=$CNICE
  C_SYSM=$CSYSM
  C_IDLE=$CIDLE
  C_SUM=$CSUM
 
  sleep $delay
 
  getline

  DIFF=`expr $CSUM - $C_SUM`
  U_USER=`echo "( $CUSER - $C_USER ) / $DIFF * 100" | bc -l | grep -E -o "[0-9]{1,2}/.[0-9]{1,2}"`
  U_NICE=`echo "( $CNICE - $C_NICE ) / $DIFF * 100" | bc -l | grep -E -o "[0-9]{1,2}/.[0-9]{1,2}"`
  U_SYSM=`echo "( $CSYSM - $C_SYSM ) / $DIFF * 100" | bc -l | grep -E -o "[0-9]{1,2}/.[0-9]{1,2}"`
  U_IDLE=`echo "( $CIDLE - $C_IDLE ) / $DIFF * 100" | bc -l | grep -E -o "[0-9]{1,2}/.[0-9]{1,2}"`

  C_USER=$CUSER
  C_NICE=$CNICE
  C_SYSM=$CSYSM
  C_IDLE=$CIDLE
  C_SUM=$CSUM
}

function stat {
  local REPEAT=1
  local DELAY=1
  if [ -n "$1" ]; then
    REPEAT=$1
  fi
 
  if [ -n "$2" ]; then
    DELAY=$2
  fi

  echo
  echo "---CPU usage statistic---"
  echo "User% Nice% System% Idle%"
  for (( i=1; i<=$REPEAT; i++ )); do
    calculate $DELAY
    echo "${U_USER}% ${U_NICE}% ${U_SYSM}% ${U_IDLE}%"

  done
  echo "-------End------"
}

function help {
cat <<-EOF
 
  Usage: $0 -h or $0 repeat_num delay_time

EOF
}
### Main part of this script ###
stat $1 $2

exit 0

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.