How can I track and log CPU and memory usage on a Mac?

Solution 1:

This mightn't quite hit the mark, but try this:

sar -o ~/output.sar 10 10 

That gathers 10 sets of metrics at 10 second intervals. You can then extract useful information from the output file (even while it's still running), for instance this will get you the disk activity for the interval you sampled:

sar -d -f ~/output.sar

Do a man sar to find out what other options there are.

Edit:

sar doesn't do memory so this will get you the free memory on your system at ten second intervals:

vm_stat 10 | awk 'NR>2 {gsub("K","000");print ($1+$4)/256000}'

You can redirect that to a file.

If you need more information, please ask.

Solution 2:

You can log CPU and memory usage of processes, though not thread count, with the Python program Syrupy.

Syrupy is a Python script that regularly takes snapshots of the memory and CPU load of one or more running processes, so as to dynamically build up a profile of their usage of system resources.

Syrupy works by one of two modes. In the first (default) mode, it monitors the resource usage of a process resulting from the execution of a user-specified command (which can be any arbitrarily-complex combination of programs and arguments that can be invoked from a shell terminal). In the second mode, Syrupy monitors the resource usage of external running processes that meet user-specified criteria: a PID (Process IDentifier) number or a command string matching a regular expression pattern.

In either case, the monitoring of the system resource usage is based on repeated calls to the system command ps.

For your use case, logging every running process, I think this command would work:

syrupy.py --poll-command='.*'

Solution 3:

You can use top and pipe data into awk or grep to read specific info you need.

Check it out here; http://ss64.com/osx/top.html

top is actually the underlying tool where Activity Monitor is build on.