Skip to content

Instantly share code, notes, and snippets.

@QNimbus
Created January 22, 2022 19:24
Show Gist options
  • Save QNimbus/5e0df94a2a4a834d22761096d1462f4f to your computer and use it in GitHub Desktop.
Save QNimbus/5e0df94a2a4a834d22761096d1462f4f to your computer and use it in GitHub Desktop.
Benchmark function that display average runtime for a command
avg_time() {
#
# usage: avg_time n command ...
#
n=$1; shift
(($# > 0)) || return # bail if no command given
for ((i = 0; i < n; i++)); do
{ time -p "$@" &>/dev/null; } 2>&1 # ignore the output of the command
# but collect time's output in stdout
done | awk '
/real/ { real = real + $2; nr++ }
/user/ { user = user + $2; nu++ }
/sys/ { sys = sys + $2; ns++}
END {
if (nr>0) printf("real %f\n", real/nr);
if (nu>0) printf("user %f\n", user/nu);
if (ns>0) printf("sys %f\n", sys/ns)
}'
}
@QNimbus
Copy link
Author

QNimbus commented Jan 22, 2022

This function can be used to benchmark the average runtime of a program. To test avg_time 5 sleep 1

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