简体   繁体   English

如何在 Linux 上获取整体 CPU 使用率(例如 57%)

[英]How to get overall CPU usage (e.g. 57%) on Linux

I am wondering how you can get the system CPU usage and present it in percent using bash, for example.例如,我想知道如何获取系统 CPU 使用率并使用 bash 以百分比表示。

Sample output:样本输出:

57%

In case there is more than one core, it would be nice if an average percentage could be calculated.如果有多个内核,最好能计算出平均百分比。

Take a look at cat /proc/stat看看cat /proc/stat

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

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.有些人认为你可以“apt-get install”任何东西。

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup.注意:这不是当前的CPU 使用率,而是自系统启动以来所有内核的总体 CPU 使用率。 This could be very different from the current CPU usage.这可能与当前的 CPU 使用率非常不同。 To get the current value top (or similar tool) must be used.要获取当前值,必须使用 top(或类似工具)。

Current CPU usage can be potentially calculated with:当前 CPU 使用率可以通过以下方式计算:

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)

You can try:你可以试试:

top -bn1 | grep "Cpu(s)" | \
           sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
           awk '{print 100 - $1"%"}'

Try mpstat from the sysstat packagesysstat包中尝试mpstat

> sudo apt-get install sysstat
Linux 3.0.0-13-generic (ws025)  02/10/2012  _x86_64_    (2 CPU)  

03:33:26 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle
03:33:26 PM  all    2.39    0.04    0.19    0.34    0.00    0.01    0.00    0.00   97.03

Then some cut or grep to parse the info you need:然后一些cutgrep来解析你需要的信息:

mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 -  $ 12}'a

Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:不妨对我的解决方案做出实际回应,这是受到 Peter Liljenberg 的启发:

$ mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
0.75%

This will use awk to print out 100 minus the 12th field (idle), with a percentage sign after it.这将使用awk打印出 100 减去第 12 个字段(空闲),其后带有一个百分号。 awk will only do this for a line where the 12th field has numbers and dots only ( $12 ~ /[0-9]+/ ). awk只会对第 12 个字段只有数字和点的行执行此操作( $12 ~ /[0-9]+/ )。

You can also average five samples, one second apart:您还可以平均间隔一秒的五个样本:

$ mpstat 1 5 | awk 'END{print 100-$NF"%"}'

Test it like this:像这样测试它:

$ mpstat 1 5 | tee /dev/tty | awk 'END{print 100-$NF"%"}'

EDITED: I noticed that in another user's reply %idle was field 12 instead of field 11. The awk has been updated to account for the %idle field being variable.编辑:我注意到在另一个用户的回复中 %idle 是字段 12 而不是字段 11。awk 已更新以说明 %idle 字段是可变的。

This should get you the desired output:这应该会得到你想要的输出:

mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { print 100 - $field }'

If you want a simple integer rounding, you can use printf:如果你想要一个简单的整数四舍五入,你可以使用 printf:

mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { printf("%d%%",100 - $field) }'

Do this to see the overall CPU usage .这样做可以查看整体 CPU 使用率 This calls python3 and uses the cross-platform psutil module .这调用python3并使用跨平台psutil模块

printf "%b" "import psutil\nprint('{}%'.format(psutil.cpu_percent(interval=2)))" | python3

The interval=2 part says to measure the total CPU load over a blocking period of 2 seconds. interval=2部分表示在 2 秒的阻塞周期内测量总 CPU 负载。

Sample output:样本输出:

9.4%

The python program it contains is this:它包含的python程序是这样的:

import psutil

print('{}%'.format(psutil.cpu_percent(interval=2)))

Placing time in front of the call proves it takes the specified interval time of about 2 seconds in this case.在调用前面放置time证明在这种情况下它需要大约 2 秒的指定间隔时间。 Here is the call and output:这是调用和输出:

$ time printf "%b" "import psutil\nprint('{}%'.format(psutil.cpu_percent(interval=2)))" | python3
9.5%

real    0m2.127s
user    0m0.119s
sys 0m0.008s

To view the output for individual cores as well , let's use this python program below.要查看单个内核的输出,让我们使用下面的这个 python 程序。 First, I obtain a python list (array) of "per CPU" information, then I average everything in that list to get a "total % CPU" type value.首先,我获得“per CPU”信息的python 列表(数组),然后对该列表中的所有内容进行平均以获得“total % CPU”类型值。 Then I print the total and the individual core percents.然后我打印总和单个核心百分比。

Python program:蟒蛇程序:

import psutil

cpu_percent_cores = psutil.cpu_percent(interval=2, percpu=True)
avg = sum(cpu_percent_cores)/len(cpu_percent_cores)
cpu_percent_total_str = ('%.2f' % avg) + '%'
cpu_percent_cores_str = [('%.2f' % x) + '%' for x in cpu_percent_cores]
print('Total: {}'.format(cpu_percent_total_str))
print('Individual CPUs: {}'.format('  '.join(cpu_percent_cores_str)))

This can be wrapped up into an incredibly ugly 1-line bash script like this if you like.如果您愿意,可以将其包装成一个非常丑陋的 1 行 bash 脚本,就像这样。 I had to be sure to use only single quotes ( '' ), NOT double quotes ( "" ) in the Python program in order to make this wrapping into a bash 1-liner work:我必须确保在 Python 程序中仅使用单引号 ( '' ),而不是双引号 ( "" ),以便将其包装成 bash 1-liner 工作:

printf "%b" "import psutil\n\
cpu_percent_cores = psutil.cpu_percent(interval=2, percpu=True)\n\
avg = sum(cpu_percent_cores)/len(cpu_percent_cores)\n\
cpu_percent_total_str = ('%.2f' % avg) + '%'\n\
cpu_percent_cores_str = [('%.2f' % x) + '%' for x in cpu_percent_cores]\n\
print('Total: {}'.format(cpu_percent_total_str))\n\
print('Individual CPUs: {}'.format('  '.join(cpu_percent_cores_str)))\n\
" | python3

Sample output: notice that I have 8 cores, so there are 8 numbers after "Individual CPUs:":示例输出:请注意我有 8 个内核,因此“Individual CPUs:”后面有 8 个数字:

Total: 10.15%
Individual CPUs: 11.00%  8.50%  11.90%  8.50%  9.90%  7.60%  11.50%  12.30%

For more information on how the psutil.cpu_percent(interval=2) python call works , see the official psutil.cpu_percent(interval=None, percpu=False) documentation here :有关psutil.cpu_percent(interval=2) python 调用如何工作的更多信息,请参阅此处的官方psutil.cpu_percent(interval=None, percpu=False)文档

psutil.cpu_percent(interval=None, percpu=False)

Return a float representing the current system-wide CPU utilization as a percentage.返回一个浮点数,以百分比表示当前系统范围的 CPU 利用率。 When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking).当间隔大于0.0时,比较间隔之前和之后经过的系统 CPU 时间(阻塞)。 When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately.当间隔为0.0None时,比较自上次调用或模块导入以来经过的系统 CPU 时间,立即返回。 That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore.这意味着第一次调用它会返回一个无意义的0.0值,你应该忽略它。 In this case it is recommended for accuracy that this function be called with at least 0.1 seconds between calls.在这种情况下,为了准确起见,建议在两次调用之间至少间隔0.1秒调用此函数。 When percpu is True returns a list of floats representing the utilization as a percentage for each CPU.当 percpu 为 True 时,返回一个浮点列表,表示每个 CPU 的利用率百分比。 First element of the list refers to first CPU, second element to second CPU and so on.列表的第一个元素指的是第一个 CPU,第二个元素指的是第二个 CPU,依此类推。 The order of the list is consistent across calls.列表的顺序在调用之间是一致的。

Warning: the first time this function is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.警告:第一次使用 interval = 0.0None调用此函数时,它将返回一个无意义的0.0值,您应该忽略该值。

References:参考:

  1. Stack Overflow: How to get current CPU and RAM usage in Python? Stack Overflow:如何在 Python 中获取当前的 CPU 和 RAM 使用情况?
  2. Stack Overflow: Executing multi-line statements in the one-line command-line? 堆栈溢出:在单行命令行中执行多行语句?
  3. How to display a float with two decimal places? 如何显示带有两位小数的浮点数?
  4. Finding the average of a list 查找列表的平均值

Related有关的

  1. https://unix.stackexchange.com/questions/295599/how-to-show-processes-that-use-more-than-30-cpu/295608#295608 https://unix.stackexchange.com/questions/295599/how-to-show-processes-that-use-more-than-30-cpu/295608#295608
  2. https://askubuntu.com/questions/22021/how-to-log-cpu-load https://askubuntu.com/questions/22021/how-to-log-cpu-load

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Linux 上获得总体 RAM 使用率(例如 57%) - How to get overall RAM usage (e.g. 57%) on Linux 如何计算好CPU百分比,例如在顶部? - How is nice cpu percentage calculated, e.g. in top? 如何通过linux curl获取远程HTTP IRI返回的RDF数据(eg DBpedia, GENEPIO...)? - How to get RDF data returned by remote HTTP IRI through linux curl (e.g. DBpedia, GENEPIO ...)? 如何搜索 Linux 手册页(例如使用 grep) - How to search Linux man pages (e.g. with grep) linux/ubuntu 中的总体 CPU 使用率和内存(RAM)使用率百分比 - overall CPU usage and Memory(RAM) usage in percentage in linux/ubuntu Linux - 更快地读取或收集文件内容(例如每秒 cpu 温度) - Linux - read or collect file content faster (e.g. cpu temp every sec.) 我如何在Linux性能下获得libc6符号(例如_int_malloc)的致电父母? - How do I get call parents for libc6 symbols (e.g. _int_malloc) with linux perf? Linux中的本机内存使用似乎比通过JVM本身(例如,通过JConsole)观察到的要高得多 - Native memory usage in Linux seems to be much higher than observed through JVM itself (e.g. through JConsole) 一个演示cmd.exe和Linux shell(例如bash),定界参数的AC程序? - A C program demonstrating how cmd.exe and a linux shell e.g. bash, delimit parameters? 如何限制Linux上的进程内存利用率(例如使用BSD :: Resource) - How to limit process memory utilization on Linux (e.g. using BSD::Resource)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM