Search code examples
macosterminalreport

CPU usage reporting in terminal


I am trying to get the CPU usage of a mac over time.

I am using this top cmd in terminal getting the result i want but would like it to output to a file and update every 5 seconds.

top -l 1 | grep -E "^CPU|^Phys"

CPU usage: 3.27% user, 14.75% sys, 81.96% idle PhysMem: 5807M used (1458M wired), 10G unused.


Solution

  • This command prints all 3 CPU usage percentages tab-separated to a file (appending line by line for each call):

    top -l1 | grep -E "CPU usage:" |  awk -v FS="CPU usage: | user, | sys, | idle" '{print $2, $3, $4}' >> cpu_user_sys_idle.tsv
    

    Works with pipe separated command chain:

    1. Top as you suggested
    2. Grep to filter only line with CPU usage
    3. Awk with variable field-separator (-v FS) using either of the 4 strings to get all percentages as isolated fields. Then print second, third and fourth (omit first since it is empty).
    4. >> redirects output appending to file (e.g. cpu_user_sys_idle.tsv)

    You additionally can put it into automated or scheduled (apple)script to collect measures in regular intervals.