[ale] bash function to show elapsed time

Todor Fassl fassl.tod at gmail.com
Fri Apr 29 18:28:16 EDT 2016


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


More information about the Ale mailing list