如何在终端 (mac) 中以 % 为单位获取 CPU 利用率 [英] How to get CPU utilization in % in terminal (mac)

查看:37
本文介绍了如何在终端 (mac) 中以 % 为单位获取 CPU 利用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 linux 和 windows 上看到过同样的问题,但在 mac(终端)上没有看到过.谁能告诉我如何以 % 为单位获取当前处理器利用率,因此示例输出将是 40%.谢谢

解决方案

这适用于 Mac(包括 %):

ps -A -o %cpu |awk '{s+=$1} END {print s "%"}'

稍微分解一下:

ps 是进程状态工具.大多数 *nix 之类的操作系统都支持它.有几个标志我们想传递给它:

  • -A 表示所有进程,而不仅仅是像您一样运行的进程.
  • -o 让我们指定我们想要的输出.在这种情况下,我们只需要 ps 输出的 cpu% 列.

这将为我们提供所有进程 cpu 使用情况的列表,例如

<前>0.01.327.00.0

我们现在需要将这个列表相加以获得最终数字,因此我们将 ps 的输出通过管道传输到 awk.awk 是一个非常强大的文本解析和操作工具.我们只是简单地将数字相加,然后打印出结果,并在末尾添加一个%".

Ive seen the same question asked on linux and windows but not mac (terminal). Can anyone tell me how to get the current processor utilization in %, so an example output would be 40%. Thanks

解决方案

This works on a Mac (includes the %):

ps -A -o %cpu | awk '{s+=$1} END {print s "%"}'

To break this down a bit:

ps is the process status tool. Most *nix like operating systems support it. There are a few flags we want to pass to it:

  • -A means all processes, not just the ones running as you.
  • -o lets us specify the output we want. In this case, it all we want to the cpu% column of ps's output.

This will get us a list of all of the processes cpu usage, like

0.0
1.3
27.0
0.0

We now need to add up this list to get a final number, so we pipe ps's output to awk. awk is a pretty powerful tool for parsing and operating on text. We just simply add up the numbers, then print out the result, and add a "%" on the end.

这篇关于如何在终端 (mac) 中以 % 为单位获取 CPU 利用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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