I am writing a program to read cpu and memory statistics from a remote host. The remote host can be Linux or Mac. So I need a command which returns the cpu/memory usage as output. I have found the command for Linux which is vmstat
. But I couldn't find a good one for Mac. I know there is one command vm_stat
on mac but it only returns memory usage. Is there a command for CPU usage as well? I have searched that most people use top
. But top is good at monitoring and it would be hard to parse the result if I analyze its output in my program. I want to use one shipped with MacOS not a third party library.
Add a comment
|
1 Answer
If you are looking to capture the total utilized CPU and Memory for all process, you could use this command that is native to Macs:
ps -A -o %cpu,%mem | awk '{ cpu += $1; mem += $2} END {print cpu , mem}'
-
1Great answer! Also, if you want a some labels on the output, you can change it to
{print "CPU: "cpu"% MEM: "mem"%"}
. That will print something likeCPU: 16.3% MEM: 75.1%
– wisbuckyCommented Jul 17, 2019 at 21:36 -
From the man page for ps command "CPU usage is currently expressed as the percentage of time spent running during the entire lifetime of a process. This is not ideal, and it does not conform to the standards that ps otherwise conforms to. CPU usage is unlikely to add up to exactly 100%." I don't think this will be matching instantaneous CPU that the poster seems to be asking for Commented Jun 12, 2021 at 14:07
-
This works great, THANK YOU. There are a lot of answers but this one worked great for Memory Usage.– AndyCommented Jul 5, 2022 at 17:28