[ale] bash function to show elapsed time

Lightner, Jeff JLightner at dsservices.com
Mon May 2 08:48:23 EDT 2016


Thanks for sharing.

It appears your intent is to run this within a script to determine how long specific sections of the script took (or at least one specific section).

The Linux "time" command can be run with any executable (binary or script) as an argument and it will give you overall time as well as system and user time.   (There was an older UNIX command called timex that did the same thing.)
e.g. "time ls -l" will output a list of files as normal then something like:
real    0m0.008s
user    0m0.003s
sys     0m0.003s


-----Original Message-----
From: ale-bounces at ale.org [mailto:ale-bounces at ale.org] On Behalf Of Todor Fassl
Sent: Friday, April 29, 2016 6:28 PM
To: Atlanta Linux Enthusiasts
Subject: [ale] bash function to show elapsed time

I've aked a lot of questions lately so I thought I'd share a function I wrote to display the elapsed time in a script. You call it at the beginning of the script to set the start time. Then you call it again to display the elapsed time. The third time you call it, it displays the total elapsed time and the time since the last call. Call it with a parameter to set the start time manually or with "0" to automatically reset the start time. For example ...
#  Set the timer
elapsed
# This will show an elapsed time of 17 seconds sleep 17 elapsed # This will show an total elapsed time of 21 seconds and a lap time of 4 seconds sleep 4 elapsed # Reset the timer elapsed 0 # This will show a total and an elapsed time of 19 seconds since the timer was reset sleep 19 elapsed #

function elapsed
	{
	test ! -z "$1" && T0="$1"
	T0=`printf "%d" $T0`
	if [ "$T0" == "0" ]; then
		T0=`date +"%s"`
		T2=$T0
	else
		T1=$T2
		T2=`date +"%s"`
		DIFF=$((T2-T0))
		HOURS=$((DIFF/3600))
		DIFF=$((DIFF-(HOURS*3600)))
		MINS=$((DIFF/60))
		SECS=$((DIFF-(MINS*60)))
		printf "Elapsed %02d:%02d:%02d, " $HOURS $MINS $SECS
		DIFF=$((T2-T1))
		HOURS=$((DIFF/3600))
		DIFF=$((DIFF-(HOURS*3600)))
		MINS=$((DIFF/60))
		SECS=$((DIFF-(MINS*60)))
		printf "%02d:%02d:%02d\n" $HOURS $MINS $SECS
	fi
	}

--
Todd
_______________________________________________
Ale mailing list
Ale at ale.org
http://mail.ale.org/mailman/listinfo/ale
See JOBS, ANNOUNCE and SCHOOLS lists at
http://mail.ale.org/mailman/listinfo



More information about the Ale mailing list