Monday, April 23, 2012

Elapsed Time for Shell Scripts

A lot of times you want to calculate the time it takes for a part of a shell script to run. Here is one of the ways you can do this:
T1=$(date +%s)
# Do something here
T2=$(date +%s)
diffsec="$(expr $T2 - $T1)"
echo | awk -v D=$diffsec '{printf "Elapsed time: %02d:%02d:%02d\n",D/(60*60),D%(60*60)/60,D%60}'
This will tell you the elapsed time between setting T1 and setting T2. The output is formatted as HH:MM:SS and printed to the console. You can easily redirect to a file for logging.

2 comments: