Last active
October 2, 2017 13:03
-
-
Save ldotlopez/0319e6102c7f6baf45748b708751d56d to your computer and use it in GitHub Desktop.
Tracking time with one-shot funcion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function __trace_time () { | |
# Call this function to trace how much time spends your code | |
# Ex: | |
# | |
# #!/bin/bash | |
# | |
# source /path/to/time-track.sh | |
# | |
# __trace_time # First call initalizes some variables and checks, | |
# # this is T-0 point | |
# | |
# some_stuff | |
# __trace_time # Check how much time `some_stuff` spent running | |
# | |
# other_stuff | |
# __trace_time # Check how much time `other_stuff` spent running | |
# # (since previous call and since T0) | |
local S="${1:-}" | |
local __TRACE_TIME_DATE_CMD="${__TRACE_TIME_DATE_CMD:-date}" | |
# First call | |
if [ -z "${__TRACE_TIME_T0:-}" ]; then | |
__TRACE_TIME_LOG_FILE="${__TRACE_TIME_LOG_FILE:-${BASH_SOURCE}.time-track}" | |
# Check if shell can handle large integers | |
[ $((1506939639262915000-1506939633986741000)) -eq 5276174000 ] || { | |
echo "Math error in shell, aborting" >&2 | |
return | |
} | |
# Check if date command can use %N format for nanoseconds | |
__TRACE_TIME_T0="$("$__TRACE_TIME_DATE_CMD" +%s%N)" | |
if ! [ "$__TRACE_TIME_T0" -eq "$__TRACE_TIME_T0" ] 2>/dev/null; then | |
echo "Support for nanoseconds missings, aborting" >&2 | |
unset __TRACE_TIME_T0 | |
return | |
fi | |
export __TRACE_TIME_T0 | |
export __TRACE_TIME_TPREV=$__TRACE_TIME_T0 | |
echo -e "delta (previous)\tdelta (from T-0)\tMessage" > "$__TRACE_TIME_LOG_FILE" | |
return | |
fi | |
local NOW="$("$__TRACE_TIME_DATE_CMD" +%s%N)" | |
local PREV_DELTA=$(($NOW-$__TRACE_TIME_TPREV)) | |
local TO_DELTA=$(($NOW-$__TRACE_TIME_T0)) | |
echo -e "${PREV_DELTA}\t${TO_DELTA}\t${S}" >> "$__TRACE_TIME_LOG_FILE" | |
export __TRACE_TIME_TPREV=$NOW | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment