2

Goal: update terminal command prompt with CPU usage statistics since last prompt appeared, e.g., jeremy@Mac:57%CPU|~/ $

Research: I know on Linux, iostat reads /proc/stat and looks for changes between checks to give accurate information. I used something like the following on CentOS:

 local cur_tick_total=$(awk 'FNR == 1 {sum=0; for (i=2; i<=NF; i++) {sum+=$i} printf "%.0f\n", sum}' /proc/stat)
 local cur_tick_idle=$(awk 'FNR == 1 {print $5}' /proc/stat)
 local delta_tick_total=$(( $cur_tick_total - $__prev_tick_total ))
 local delta_tick_idle=$(( $cur_tick_idle - $__prev_tick_idle ))
 local percent_idle=$(( $delta_tick_idle * 100 / $delta_tick_total ))
 __cpu=$(( 100 - $percent_idle ))

Question: How can I do this on Mac? If iostat works the same way as on Linux, it has to read from somewhere like this, but /proc/stat doesn't exist on Mac. I want to know where it looks to be able to read from that location myself as part of my PS1.

Edit: iostat's output does not work for my purposes, since it outputs either system load average, which is a nonsense number or CPU % usages since system boot, which is not helpful to me. I want a more instantaneous actual CPU usage metric that I can get instantly via the command line.

  • AFAIK there is no similar user-readable structure on macOS. You can call iostat from PS1 or PROMPT_COMMAND though. – nohillside Oct 29 '18 at 21:44
  • iostat does not perform the same functions. Calling iostat once gives you average usage since last boot (and some load averages). I want the cpu usage since last command prompt appearance. Is there any way to get this functionality? – jeremysprofile Oct 29 '18 at 21:47
  • Parsing the output of uptime might be an option. – nohillside Oct 30 '18 at 6:45
  • 1
    powermetrics might be an option (judging from the man page). Or other commands where the man page mentions "cpu" (grep cpu /usr/share/man/man1/*) – nohillside Oct 31 '18 at 15:57
  • 1
    @nohillside, in case you're curious, here's what I've got working – jeremysprofile Nov 7 '18 at 21:34

You must log in to answer this question.

Browse other questions tagged .