Wednesday, May 11, 2011

Shell script to capture cpu and memory usage of a process at certain intervals of time


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

#!/bin/bash

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

pid=$1

# maxRunTime is used to control the maximum no of seconds for which to run this script.
maxRunTime=72000
# sleepTime is used to sleep for specified seconds, to take the memory dump again
sleepTime=30

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:

Post a Comment