Wednesday, September 8, 2010

Dump cpu and memory usage of a process

Here is the automated shell script which can dump the memory and cpu usage of a process. Helpful in cases when you want to monitor a process for a long time.

#!/bin/bash

if [ "$#" -ne 1 ]; then
echo "Usage ... [$0 <pid>]"
exit
fi

pid=$1

# maxRunTime is used to control the script, so that it run only for specified number of seconds
maxRunTime=72000
# sleepTime is used to sleep for specified seconds, to take the memory dump again
sleepTime=120

logFile=${pid}_process.log
commandFile=${pid}_command.log

`ptree $pid >> $commandFile`;
`pargs $pid >> $commandFile`;

currentRunTime=0

while [ $currentRunTime -lt $maxRunTime ]
do
time=`date +%F::%X | tr -d '[\n]'`
line=`ps -eo pid,pcpu,vsz | grep $pid`;
echo "$time $line" >> $logFile
sleep $sleepTime
currentRunTime=`expr $currentRunTime + $sleepTime`
echo "Execution Time : ${currentRunTime} seconds [max ${maxRunTime}]"
done;

No comments: