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

发布于 2025-01-04 04:35:24 字数 1549 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

拧巴小姐 2025-01-11 04:35:24

看一下 cat /proc/stat

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {打印用法“%”}'

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

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

当前 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)

Take a look at 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.

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.

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)
只想待在家 2025-01-11 04:35:24

您可以尝试:

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

You can try:

top -bn1 | grep "Cpu(s)" | \
           sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
           awk '{print 100 - $1"%"}'
一个人的夜不怕黑 2025-01-11 04:35:24

尝试使用 sysstat 包中的 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

然后进行一些 cutgrep 来解析您需要的信息:

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

Try mpstat from the sysstat package

> 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 cutor grepto parse the info you need:

mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 -  $ 12}'a
平定天下 2025-01-11 04:35:24

不妨用我的解决方案提出一个实际的响应,该解决方案受到 Peter Liljenberg 的启发:

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

这将使用 awk 打印出 100 减去第 12 个字段(空闲),并在其后面带有百分号。 awk 只会对第 12 个字段仅包含数字和点的行执行此操作 ($12 ~ /[0-9]+/)。

您还可以平均五个样本,间隔一秒:

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

像这样测试:

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

Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:

$ 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 will only do this for a line where the 12th field has numbers and dots only ($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"%"}'
梦明 2025-01-11 04:35:24

编辑:我注意到在另一个用户的回复中 %idle 是字段 12 而不是字段 11。 awk 已更新以考虑到 %idle 字段是可变的。

这应该会得到您想要的输出:

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

如果您想要简单的整数舍入,您可以使用 printf:

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

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.

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:

mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { printf("%d%%",100 - $field) }'
睫毛溺水了 2025-01-11 04:35:24

执行此操作可以查看整体 CPU 使用率。这会调用 python3 并使用跨平台 psutil 模块< /a>.

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

interval=2 部分表示测量 2 秒阻塞期内的总 CPU 负载。

示例输出:

9.4%

它包含的 python 程序是这样的:

import psutil

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

time 放在调用前面证明在这种情况下它需要大约 2 秒的指定间隔时间。以下是调用和输出:

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

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

要查看各个内核的输出,让我们使用下面的 python 程序。首先,我获得“每个 CPU”信息的 python 列表(数组),然后对该列表中的所有内容进行平均以获得“总 % CPU”类型值。然后我打印总数和单个核心百分比。

Python 程序:

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)))

如果您愿意,可以将其包装成一个极其丑陋的单行 bash 脚本。我必须确保在 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

示例输出:请注意,我有 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%

有关如何 psutil.cpu_percent(interval=2) 的更多信息蟒蛇调用有效,请参阅官方 psutil.cpu_percent(interval=None, percpu=False) 此处的文档

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

返回一个浮点数,以百分比形式表示当前系统范围的 CPU 利用率。当间隔>时0.0 比较间隔(阻塞)前后所用的系统 CPU 时间。当间隔为 0.0None 时,比较自上次调用或模块导入以来经过的系统 CPU 时间,并立即返回。这意味着第一次调用它时,它将返回一个无意义的 0.0 值,您应该忽略该值。在这种情况下,为了准确性,建议在调用之间至少间隔 0.1 秒调用此函数。当 percpu 为 True 时,返回一个浮点数列表,表示每个 CPU 的利用率百分比。列表的第一个元素指第一个 CPU,第二个元素指第二个 CPU,依此类推。列表的顺序在调用之间保持一致。

警告:第一次使用 Interval = 0.0None 调用此函数时,它将返回无意义的 0.0 code> 您应该忽略的值。

更进一步:

我在 cpu_logger.py 中使用上述代码我的 eRCAGuy_dotfiles 存储库。

参考资料:

  1. Stack Overflow:如何在 Python 中获取当前 CPU 和 RAM 使用情况?
  2. 堆栈溢出:在一行命令行中执行多行语句?
  3. 如何显示具有两位小数的浮点数?
  4. 查找列表的平均值

相关

  1. https://unix.stackexchange。 com/questions/295599/如何显示使用超过 30-cpu 的进程/295608#295608
  2. https://askubuntu.com/questions/22021/how-to-log-cpu-load< /a>

Do this to see the overall CPU usage. This calls python3 and uses the cross-platform psutil module.

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.

Sample output:

9.4%

The python program it contains is this:

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. 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. 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. 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. 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:

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:":

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=None, percpu=False)

Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case it is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. 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.

Going further:

I use the above code in my cpu_logger.py script in my eRCaGuy_dotfiles repo.

References:

  1. Stack Overflow: How to get current CPU and RAM usage in Python?
  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
  2. https://askubuntu.com/questions/22021/how-to-log-cpu-load
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文