Calculating Elapsed Time in Unix

Published by Utkarsh Patel on 08/02/09 16:32:31
Last edited on 27/04/09 20:59:43

A frequent need for many developers and even a lot of users is to find out how long it took a script to execute. Many do this by displaying, emailing, etc. the start and end time of each script. The reader is then faced with subtracting the two times to determine run time. The following scripts removes this manual step and calculates runtime for the user.

#!/bin/ksh
startdate=$1
enddate=$2
((start_seconds = $(expr substr "$startdate" 1 2)*3600 + $(expr substr "$startdate" 4 2)*60 + $(expr substr "$startdate" 7 2)))
((end_seconds = $(expr substr "$:qenddate" 1 2)*3600 + $(expr substr "$enddate" 4 2)*60 + $(expr substr "$enddate" 7 2)))
((elapsed_seconds = end_seconds - start_seconds))                                                                                  
if then ((elapsed_seconds += 86400)) fi echo Elapsed time of $((elapsed_seconds / 3600)):$(((elapsed_seconds - ((elapsed_seconds/3600)*3600)) / 60)):$((elapsed_seconds % 60))

I saved the file as run_time.sh

This is how the script would be used in a program

startTime=`date +"%H:%M:%S"`
[program code]
endTime=`date +"%H:%M:%S"`
run_time.sh $startTime $endTime >> /tmp/temp.txt

This example would redirect the output to a file in /tmp/ folder. You might want to email the file to the user with other data to give them the run time of the script or display it to the screen if you are testing how long your script will take. There are various options available to you.

About the Author

Utkarsh Patel is one of our newest members, and he could not have come at a better time. He has helped bring back stability and control to Techlicity Ventures during our rapid growth. If he isn't marvelling at a recently discovered Oracle feature or technique he is bothering the rest of the team on why we should move everything over to Oracle databases. Utkarsh complements the team well with his determination and sound research.

Bookmark and Share
Blog Widget by LinkWithin
blog comments powered by Disqus

Valid XHTML 1.0!