How to Measure the Length of Execution of a Selected Portion of Code in Bash
The aim of this page📝 is to share a simple way of measuring the duration of a selected portion of code execution in bash.
1 min readJan 13, 2023
- I am using
ms
unit - To get the absolute timestamp, use
$(date +%s%N | cut -b1-13)
%s
for seconds since the UNIX epoch%N
adding nanosecond portioncut
is selecting the first 13 fields of the nanosecond portion => milliseconds
/$ date +%s
1673595770
/$ date +%s%N
1673595775334609500
/$ $(date +%s%N | cut -b1-13)
1673595775334
- Get the absolute timestamp at the beginning of the program
- Get the absolute timestamp at the end of the program
- Subtract
end - beginning
to get the duration - print it
start_prog=$(date +%s%N | cut -b1-13)
#PROGRAM
end_prog=$(date +%s%N | cut -b1-13)
prog_time_ms=$(("$end_prog" - "$start_prog"))
echo "INFO: prog finished in '${prog_time_ms} ms'"
…you could also do date +%s%3N
/$ date +%s%3N
1673596128544