Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 680
cyw Avatar asked Jun 15 '15 21:06

cyw


People also ask

How do I find my CPU on Mac?

First, click the Apple menu at the upper left, and then click “About This Mac.” In the menu that appears, you'll get a quick roundup of your Mac's specifications, including the type of CPU it has next to “Processor.” In the image below, we see this iMac has a 3.5 GHz Quad-Core Intel Core i7 CPU.


2 Answers

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.

like image 143
vcsjones Avatar answered Oct 26 '22 02:10

vcsjones


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)

like image 22
Jon R Avatar answered Oct 26 '22 04:10

Jon R