diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2012-07-30 13:43:45 +0200 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2012-07-30 13:43:45 +0200 |
commit | 765ede8f464dd00ea7e96c5d075557f5c90179db (patch) | |
tree | 283a67a0d8a1a1d7f1a9d9601fcdd70e5dd14f1f /timer | |
parent | 320b98ea3af954cec43149cbcb9bc255134bb43c (diff) | |
download | bin-765ede8f464dd00ea7e96c5d075557f5c90179db.zip bin-765ede8f464dd00ea7e96c5d075557f5c90179db.tar.gz |
add timer: timer function in bash
Diffstat (limited to 'timer')
-rwxr-xr-x | timer | 39 |
1 files changed, 39 insertions, 0 deletions
@@ -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 |