Chinaunix首页 | 论坛 | 博客
  • 博客访问: 319767
  • 博文数量: 96
  • 博客积分: 230
  • 博客等级: 二等列兵
  • 技术积分: 722
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-13 22:25
个人简介

心安处即吾乡!

文章分类

全部博文(96)

文章存档

2016年(1)

2014年(79)

2013年(7)

2012年(9)

我的朋友

分类: Python/Ruby

2012-04-18 19:31:31

点击(此处)折叠或打开

  1. #!/bin/bash
  2. # by Paul Colby (http://colby.id.au), no rights reserved ;)

  3. PREV_TOTAL=0
  4. PREV_IDLE=0

  5. while true; do
  6.  CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.

  7. #echo "${CPU[0]}";
  8. # echo "${CPU[1]}";
  9. # echo "${CPU[2]}";
  10. # echo "${CPU[3]}";
  11. # echo "${CPU[4]}";

  12.  unset CPU[0] # Discard the "cpu" prefix.
  13.  IDLE=${CPU[4]} # Get the idle CPU time.

  14.  # Calculate the total CPU time.
  15.  TOTAL=0
  16.  for VALUE in "${CPU[@]}"; do
  17.   let "TOTAL=$TOTAL+$VALUE"
  18.  done

  19. # echo $TOTAL;

  20.  # Calculate the CPU usage since we last checked.
  21.  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  22.  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  23.  #获取不带小数的百分比
  24.  #let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
  25.  #echo -en "\rCPU: $DIFF_USAGE% \b\b"

  26.  #获取带小数的百分比
  27.  let "DIFF_USAGE=1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL"
  28.  let "DIFF_USAGE_UNITS=$DIFF_USAGE/10"
  29.  let "DIFF_USAGE_DECIMAL=$DIFF_USAGE"
  30.  echo -en "\rCPU: $DIFF_USAGE_UNITS.$DIFF_USAGE_DECIMAL% \b\b\b\b"

  31.  # Remember the total and idle CPU times for the next check.
  32.  PREV_TOTAL="$TOTAL"
  33.  PREV_IDLE="$IDLE"

  34.  # Wait before checking again.
  35. sleep 1
  36. done
使用方法:/bin/bash cpu_usage.sh
CPU: 7.3%
注意:以上脚本只能手动结束运行
阅读(3167) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~