使用命令显示CPU使用率

我想查看CPU使用情况。
我使用了这个命令:
top -bn1 | grep "Cpu(s)" | 
           sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | 
           awk '{print 100 - $1}'

但它返回100%。 正确的方式是什么?
3个回答

为什么不使用htop(交互式进程查看器)?要安装它,打开终端窗口并输入以下命令:
sudo apt-get install htop

另外请参考 man htop 以获取更多信息和设置方法。

enter image description here enter image description here


要获取CPU使用率,最好的方法是读取/proc/stat文件。查看man 5 proc获取更多帮助。

我在这里找到了由Paul Colby编写的有用脚本here

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

PREV_TOTAL=0
PREV_IDLE=0

while true; do

  CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
  unset CPU[0]                          # Discard the "cpu" prefix.
  IDLE=${CPU[4]}                        # Get the idle CPU time.

  # 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"
  echo -en "\rCPU: $DIFF_USAGE%  \b\b"

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

  # Wait before checking again.
  sleep 1
done

将其保存为cpu_usage,添加执行权限chmod +x cpu_usage并运行:
./cpu_usage

按下 Ctrl+c 停止脚本。

它在tx.2large EC2实例上始终显示为0%。问题出在哪里?而CloudWatch显示为23%。 - Himanshu Bansal

我找到了一个很好的解决方案,这是它:
top -bn2 | grep '%Cpu' | tail -1 | grep -P  '(....|...) id,' 

我不确定,但在我看来,带有“-n”参数的top的第一次迭代返回一些虚拟数据,在我所有的测试中都是相同的。
如果我使用-n2,那么第二个框架总是动态的。所以顺序是:
1. 获取top -bn2的前两个框架。 2. 然后从这些框架中只取包含“%Cpu”的行:grep '%Cpu' 3. 然后只取最后一次出现/行:`tail -1` 4. 然后获取空闲值(有4或5个字符,一个空格,“id,”):grep -P '(....|...) id,' 希望对你有所帮助, 保罗

enter image description here


1不是真正的“虚拟数据”,但是是的,top 的第一次迭代没有以前的样本来比较数据,因此看起来像是胡言乱语。请参考这个评论 - Campa