From 765ede8f464dd00ea7e96c5d075557f5c90179db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Zurcher?= Date: Mon, 30 Jul 2012 13:43:45 +0200 Subject: add timer: timer function in bash --- timer | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100755 timer diff --git a/timer b/timer new file mode 100755 index 0000000..e47bbcb --- /dev/null +++ b/timer @@ -0,0 +1,39 @@ +#! /bin/bash +# +# Elapsed time. Usage: +# +# t=$(timer) +# ... # do something +# printf 'Elapsed time: %s\n' $(timer $t) +# ===> Elapsed time: 0:01:12 +# +# +##################################################################### +# If called with no arguments a new timer is returned. +# If called with arguments the first is used as a timer +# value and the elapsed time is returned in the form HH:MM:SS. +# +function timer() +{ + if [[ $# -eq 0 ]]; then + echo $(date '+%s') + else + local stime=$1 + etime=$(date '+%s') + + if [[ -z "$stime" ]]; then stime=$etime; fi + + dt=$((etime - stime)) + ds=$((dt % 60)) + dm=$(((dt / 60) % 60)) + dh=$((dt / 3600)) + printf '%d:%02d:%02d' $dh $dm $ds + fi +} + +# If invoked directly run test code. +if [[ $(basename $0 .sh) == 'timer' ]]; then + t=$(timer) + read -p 'Enter when ready...' p + printf 'Elapsed time: %s\n' $(timer $t) +fi -- cgit v1.1-2-g2b99