public
Last active

  • Download Gist
Track CPU usage by PID over time
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#!/bin/bash
# --- Version history ---
# 0.4: added variable to store file path, and $2 for base file name
# added variable to store desired reporting interval
# 0.3: added $1 to send in process ID at run time.
# 0.2: switched to $SECONDS for the loop. works.
# 0.1: didn't work well at all.
# --- Version history ---
 
# Usage: cputrack [PID] [filename]
# replace [PID] with process ID #
# replace [filename] with base file name to use (no extension)
 
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 3
mydate=`date "+%H:%M:%S"`
done

Hey, nice script. I have a couple of questions:
1. Could you modify this to monitor memory usage instead of CPU?
2. Could you make a version for a specific function call, so that the usage would be:
memorytrack "myexec myarg1 myarg2" [filename]

I guess the question I really have is how to get a PID automatically from a command-line call. =)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.