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.
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
Mac OS X Hints
http://hints.macworld.com/article.php?story=2009102906322976