Record CPU usage for a given process over time

Oct 29, '09 07:30:05AM

Contributed by: robg

For an upcoming project involving virtualization applications, I wanted an easy way to record the CPU usage for a given program over time.

I'm aware of the Instruments program included in the Xcode Developer Tools, but I was looking for something simple, that I could run without a lot of overhead, and that would just record data for further analysis in Excel.

After a bit of digging with Google, I didn't find anything that quite worked (a friend tells me that mrtg and Cacti should handle this; I haven't tried them yet), so I created a relatively simple bash script to get the job done - special thanks to Keith Bradnam for assistance in making it more interactive.

The program reports on a chosen program (process ID, actually) at a specified interval, then saves a few items (timestamp, process ID, CPU usage, and command name) to a text file, in this format:

20:20:39 29916  15.7 firefox-bin
20:20:41 29916   4.0 firefox-bin
20:20:43 29916  48.6 firefox-bin
The program does not create pretty graphs, or do any sort of analysis -- that part is up to you! However, with the data, you can do some interesting things. For instance, the graph above (click it for a much larger version) shows Firefox's CPU usage while browsing and playing a few Flash games on my MacBook Pro for ten minutes or so.

Read on for the details...

Here's the code I created:

#!/bin/bash
# Usage: cputrack [PID#] [filename]

filepath=/Users/your_user/Desktop   # modify as desired
interval=20                         # reports per minute
timelimit=6000                      # how long to run, in seconds

mydate=`date "+%H:%M:%S"`           # the timestamp
freq=$((60/$interval))              # for sleep function

while [ "$SECONDS" -le "$timelimit" ] ; do
  ps -p$1 -opid -opcpu -ocomm -c | grep $1 | sed "s/^/$mydate /" >> $filepath/$2.txt
  sleep $freq
  mydate=`date "+%H:%M:%S"`
done
(As I expect I'll be modifying this script over time, I've also posted it on gist.github; that's where the newest version will always reside.)

To use, copy and paste the code into a pure text editor, and change the variables to your liking. Then save it somewhere on your path, make it executable (chmod a+x cputrack), and then call it with both the process ID you wish to track and the base name (not including the extension) of the file you'd like it to create: cputrack 123 cpu_someapp.

If you have suggestions for improvements, please post them -- I know there's a lot more that can be done for error checking, taking user input, etc., but I wanted something simple and fast, and this works for my needs.

Comments (12)


Mac OS X Hints
http://hints.macworld.com/article.php?story=2009102906322976