Skip to content

Instantly share code, notes, and snippets.

@darrarski
Created July 25, 2024 15:50
Show Gist options
  • Save darrarski/f3e1fb836a82cd13279631984b2c11c0 to your computer and use it in GitHub Desktop.
Save darrarski/f3e1fb836a82cd13279631984b2c11c0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Measure time
# Usage: stopwatch [start|stop|print]
function stopwatch {
case "$1" in
start)
# start new stopwatch
STOPWATCH+=($(date -u +%s))
;;
stop)
# stop last started stopwatch
if [[ ${#STOPWATCH[@]} > 0 ]]; then
unset STOPWATCH[$((${#STOPWATCH[@]}-1))]
fi
;;
print)
# print last started (but not stopped) stopwatch's elapsed time
if [[ ! -z $STOPWATCH ]]; then
local start=${STOPWATCH[$((${#STOPWATCH[@]}-1))]}
local now=$(date -u +%s)
local elapsed=$((now-start))
local hours=$((elapsed/3600))
local minutes=$((elapsed%3600/60))
local seconds=$((elapsed%60))
printf '%.0f:%2.0f:%2.0f' $hours $minutes $seconds | tr ' ' '0'
fi
;;
esac
}
# Example usage:
function taskA {
echo "Task A started"
stopwatch start
sleep 2
echo "Task A finished in $(stopwatch print)"
stopwatch stop
}
function taskB {
echo "Task B started"
stopwatch start
local i
for ((i=1; i<=3; i++)); do
sleep 1
if [[ $i == 2 ]]; then
taskC
fi
done
echo "Task B finished in $(stopwatch print)"
stopwatch stop
}
function taskC {
echo "Task C started"
stopwatch start
local i
for ((i=1; i<=3; i++)); do
sleep 1
done
echo "Task C finished in $(stopwatch print)"
stopwatch stop
}
stopwatch start
taskA
sleep 1
taskB
echo "Total time: $(stopwatch print)"
# Output:
# Task A started
# Task A finished in 0:00:02
# Task B started
# Task C started
# Task C finished in 0:00:03
# Task B finished in 0:00:06
# Total time: 0:00:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment