简体   繁体   中英

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

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.

Adding up all those CPU % can give a number > 100% (probably multiple cores).

Here's a simpler method, although it comes with some problems:

top -l 2 | grep -E "^CPU"

This gives 2 samples, the first of which is nonsense (because it calculates CPU load between samples).

Also, you need to use RegEx like (\\d+\\.\\d*)% or some string functions to extract values, and add "user" and "sys" values to get the total.

(From How to get CPU utilisation, RAM utilisation in MAC from commandline )

Building upon @Jon R's answer, we can pick up the user CPU utilization through some simple pattern matching

top -l 1 | grep -E "^CPU" | grep -Eo '[^[:space:]]+%' | head -1

And if you want to get rid of the last % symbol as well,

top -l 1 | grep -E "^CPU" | grep -Eo '[^[:space:]]+%' | head -1 | sed s/\%/\/

你可以这样做。

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

Building on previous answers from @Jon R. and @Rounak D, the following line prints the sum of user and system values, with the added percent. I've have tested this value and I like that it roughly tracks well with the percentages shown in the macOS Activity Monitor .

top -l  2 | grep -E "^CPU" | tail -1 | awk '{ print $3 + $5"%" }'

You can then capture that value in a variable in script like this:

cpu_percent=$(top -l  2 | grep -E "^CPU" | tail -1 | awk '{ print $3 + $5"%" }')

PS: You might also be interested in the output of uptime, which shows system load.

top -F -R -o cpu

-F Do not calculate statistics on shared libraries, also known as frameworks.

-R Do not traverse and report the memory object map for each process.

-o cpu Order by CPU usage

Answer Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM