如何使用 bash 获取处理器使用百分比? [英] How to get percentage of processor use with bash?

查看:21
本文介绍了如何使用 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 上找到的,但是它非常不精确我试图做更多的改进不能,有没有人知道有什么方法可以得到% 0-100的CPU利用率百分比

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
" "$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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆