Skip to content

Instantly share code, notes, and snippets.

@AfroThundr3007730
Last active December 9, 2024 07:21
Show Gist options
  • Save AfroThundr3007730/48156633e3d2b8ac6594281057c6e125 to your computer and use it in GitHub Desktop.
Save AfroThundr3007730/48156633e3d2b8ac6594281057c6e125 to your computer and use it in GitHub Desktop.
Bash function to record duration, with concurrent timer support
#!/bin/bash
# Record time duration, concurrent timers
timer() {
[[ $1 =~ ^[0-9]+$ ]] && {
[[ $n -gt $1 ]] || n=$1; local i=$1; shift; }
[[ $1 == -n ]] && { n=$(( n + 1 )); shift; }
[[ $1 == -p ]] && { n=$(( n - 1 )); shift; }
[[ $1 == -c ]] && { local i=$n; shift; }
[[ -n $1 ]] || say -n err 'No timer action specified.'
[[ $1 == start ]] && tstart[$i]=$SECONDS
[[ $1 == stop ]] && {
[[ -n ${tstart[$i]} ]] || say -n err 'Timer %s not started.' "$i"
tstop[$i]=$SECONDS; duration[$i]=$(( tstop[i] - tstart[i] )); }
[[ $1 == show ]] && {
[[ -n ${tstop[$i]} ]] || duration[$i]=$(( SECONDS - tstart[i] ))
echo ${duration[$i]}; }
return 0
}
@AfroThundr3007730
Copy link
Author

This uses my say function from before, but those lines could be changed to use printf instead.

@AfroThundr3007730
Copy link
Author

Updated version in my utility functions module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment