如何通过bash获取处理器使用率? [英] How to get percentage of processor use with bash?
问题描述
我想知道如何将处理器使用率的百分比从0%提高到100%?
I wonder how do I get the percentage of my processor usage from 0% to 100%?
知道最好使用bash或其他方法使用我的处理器的百分比是多少.
to know how many percent'm using my processor preferably in bash or other methods provided that percentage.
我有我在Google上找到的这个脚本,但是它是非常不精确的 我试图做更多的改进,没有人知道有什么方法可以使CPU利用率百分比达到0-100.
I have this script that I found on google however it is very much imprecisso I tried to make more improvements could not, does anyone know any method to get the percentage of CPU utilization in% 0-100
我的脚本
NUMCPUS=`grep ^proc /proc/cpuinfo | wc -l`; FIRST=`cat /proc/stat | awk '/^cpu / {print $5}'`; sleep 1; SECOND=`cat /proc/stat | awk '/^cpu / {print $5}'`; USED=`echo 2 k 100 $SECOND $FIRST - $NUMCPUS / - p | dc`; echo ${USED}% CPU Usage
推荐答案
处理器使用或利用率是对时间的衡量.测量%
中利用率的一种方法是通过对/proc/stat
的两个连续读取进行计算.一个简单的通用bash脚本来计算百分比是:
Processor use or utilization is a measurement over time. One way to measure utilization in %
is by computation over two successive reads of /proc/stat
. A simple common bash script to compute the percentage is:
#!/bin/bash
# Read /proc/stat file (for first datapoint)
read cpu user nice system idle iowait irq softirq steal guest< /proc/stat
# compute active and total utilizations
cpu_active_prev=$((user+system+nice+softirq+steal))
cpu_total_prev=$((user+system+nice+softirq+steal+idle+iowait))
usleep 50000
# Read /proc/stat file (for second datapoint)
read cpu user nice system idle iowait irq softirq steal guest< /proc/stat
# compute active and total utilizations
cpu_active_cur=$((user+system+nice+softirq+steal))
cpu_total_cur=$((user+system+nice+softirq+steal+idle+iowait))
# compute CPU utilization (%)
cpu_util=$((100*( cpu_active_cur-cpu_active_prev ) / (cpu_total_cur-cpu_total_prev) ))
printf " Current CPU Utilization : %s\n" "$cpu_util"
exit 0
使用/输出:
$ bash procstat-cpu.sh
Current CPU Utilization : 10
经过5次迭代的输出:
$ ( declare -i cnt=0; while [ "$cnt" -lt 5 ]; do bash procstat-cpu.sh; ((cnt++)); done )
Current CPU Utilization : 20
Current CPU Utilization : 18
Current CPU Utilization : 18
Current CPU Utilization : 18
Current CPU Utilization : 18
这篇关于如何通过bash获取处理器使用率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!