问题
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 ofps
'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