Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find elapsed time of script execution

Status
Not open for further replies.

gotchausa

Programmer
Jan 24, 2002
64
CA
I need to determine how long it takes for a script to execute within the actual script, then print this out. Is there any way of doing this?

The command 'time' can only be used from the unix prompt, e.g
# time <script_name>

I want to be able to have something in my script that records a start time, an end time when the script finishes, and then work out the elapsed time.

Thx.
 
Are you worried about times below a second? If not, then why not just use the following:

START=`date +%s`
# do whatever
END=`date +%s`
TIME=$(($END - $START))
echo &quot;The elapsed time was $TIME seconds&quot;
 
Thanks.
This script only works if the time elapsed is less than a minute. Also, if the start time is lets say 45 secs and the end time is 5 secs (meaning elapsed time was 20 secs), the variable $TIME would result in a negative value.
 
No, the %s format parameter (not %S) returns the number of seconds since 1970/01/01 00:00:00 UTC.

Note: this parameter is not available on all unix's
(eg sco openserver 5.0.x)

stan hubble

 
OK...it's not supported on the Solaris that I'm using (2.6 and 8.0).
Do you know of an alternative solution?
 
If you are going to using Perl, just use the 'time' function. Here's how you could use perl within a Bourne shell script.

START=`perl -e 'print time'`
sleep 5
END=`perl -e 'print time'`
TIME=$(($END - $START))
 
If you are certain that your script will run less that a day, you can use the following:


hr=$(date +%H)
mn=$(date +%M)
sc=$(date +%S)
startTime=$(($hr*3600+$mn*60+$sc))
echo &quot;Starting at $startTime seconds&quot;

# put your script to time here
find / -name file -print

hr=$(date +%H)
mn=$(date +%M)
sc=$(date +%S)
endTime=$(($hr*3600+$mn*60+$sc))
echo &quot;Ending at $endTime seconds&quot;
elapsedTime=$(($endTime-$startTime))
echo &quot;Total elapsed time is $elapsedTime seconds&quot;


You could easily modify this script to add 86400 seconds to startTime if the start hour is greater than the end hour (meaning that midnight has passed during the execution of the timing script)

Hope this helps. Einstein47
(Love is like PI - natural, irrational, endless, and very important.)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top