How to get cpu/memory usage from command line output

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.


Solution 1:

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}'