Skip to content

Instantly share code, notes, and snippets.

@managai
Created October 17, 2011 11:12
Show Gist options
  • Save managai/1292409 to your computer and use it in GitHub Desktop.
Save managai/1292409 to your computer and use it in GitHub Desktop.
(bash) Measure Elapsed Time
#!/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
}
start=$(timer)
# some code to execute...
elapsed=$(timer $start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment