如何在 Linux 上获得整体 CPU 使用率(例如 57%) [英] How to get overall CPU usage (e.g. 57%) on Linux

查看:29
本文介绍了如何在 Linux 上获得整体 CPU 使用率(例如 57%)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何获取系统 CPU 使用率并使用 bash 以百分比形式显示它,例如.

I am wondering how you can get the system CPU usage and present it in percent using bash, for example.

示例输出:

57%

如果有多个核心,如果可以计算平均百分比就好了.

In case there is more than one core, it would be nice if an average percentage could be calculated.

推荐答案

看一看cat/proc/stat

grep 'cpu'/proc/stat |awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

编辑请在复制粘贴或将其用于任何严肃的工作之前阅读评论.这没有经过测试或使用,对于不想安装实用程序或在任何发行版中都可以使用的东西的人来说,这是一个想法.有些人认为你可以apt-get install"任何东西.

EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.

注意:这不是当前 CPU 使用率,而是自系统启动以来所有内核的总体 CPU 使用率.这可能与当前的 CPU 使用率非常不同.要获取当前值,必须使用 top(或类似工具).

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.

当前的 CPU 使用率可以通过以下方式计算:

Current CPU usage can be potentially calculated with:

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' 
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)

这篇关于如何在 Linux 上获得整体 CPU 使用率(例如 57%)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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