A small shell function that can be added before commands to measure their time:
#!/bin/bash
tm_date() {
local start
start=$(date +%s)
"$@"
local exit_code=$?
echo >&2 "took ~$(($(date +%s) - start)) seconds. exited with ${exit_code}."
return $exit_code${exit_code}
}
tm_secs() {
local start=$EPOCHSECONDS
"$@"
local exit_code=$?
echo >&2 "took ~$((EPOCHSECONDS - start)) seconds. exited with ${exit_code}."
return $exit_code${exit_code}
}
tm_millisecs() {
local start=${EPOCHREALTIME/./}
"$@"
local exit_code=$?
echo >&2 "took ~$(( (${EPOCHREALTIME/./} - start)/1000 )) milliseconds. exited with ${exit_code}."
return ${exit_code}
}
tm_microsecs() {
local start=${EPOCHREALTIME/./}
"$@"
local exit_code=$?
echo >&2 "took ~$((${EPOCHREALTIME/./} - start)) microseconds. exited with ${exit_code}."
return $exit_code${exit_code}
}
Then use it in your script, or on your command line like so:
tm the_original_command with all its parameters
For example,
tm_date sleep 1
tm_secs sleep 1
tm_millisecs sleep 1
tm_microsecs sleep 1
Will output,
took ~1 seconds. exited with 0.
took ~1 seconds. exited with 0.
took ~1002 milliseconds. exited with 0.
took ~1001608~1001540 microseconds. exited with 0.