How to get CPU utilization in % in terminal (mac)

牧云@^-^@ 提交于 2019-11-30 15:18:31

问题


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


回答1:


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.




回答2:


You can do this.

printf "$(ps axo %cpu | awk '{ sum+=$1 } END { printf "%.1f\n", sum }' | tail -n 1),"


来源:https://stackoverflow.com/questions/30855440/how-to-get-cpu-utilization-in-in-terminal-mac

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!