Mor*_*yan 20 server command-line cpu
我想查看 CPU 使用率。
我使用了这个命令:
top -bn1 | grep "Cpu(s)" |
sed "s/.*, *\([0-9.]*\)%* id.*/\1/" |
awk '{print 100 - $1}'
Run Code Online (Sandbox Code Playgroud)
但它返回 100%。
正确的方法是什么?
v2r*_*v2r 40
为什么不使用htop[交互式进程查看器]?为了安装它,打开一个终端窗口并输入:
sudo apt-get install htop
Run Code Online (Sandbox Code Playgroud)
另请参阅man htop以获取更多信息以及如何设置它。

gir*_*ngo 15
要获取 CPU 使用率,最好的方法是读取 /proc/stat 文件。查看man 5 proc更多帮助。
我在这里找到了 Paul Colby 写的一个有用的脚本
#!/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
Run Code Online (Sandbox Code Playgroud)
将其保存到cpu_usage,添加执行权限chmod +x cpu_usage并运行:
./cpu_usage
Run Code Online (Sandbox Code Playgroud)
停止脚本,点击Ctrl+c
小智 6
我找到了一个很好用的解决方案,这里是:
top -bn2 | grep '%Cpu' | tail -1 | grep -P '(....|...) id,'
Run Code Online (Sandbox Code Playgroud)
我不确定,但在我看来,top带-n参数的第一次迭代返回一些虚拟数据,在我的所有测试中总是相同的。
如果我使用,-n2那么第二帧总是动态的。所以顺序是:
top -bn2grep '%Cpu'grep -P '(....|...) id,'希望它有所帮助,保罗