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.

Pavol Kutaj
1 min readJan 13, 2023
  1. I am using ms unit
  2. To get the absolute timestamp, use $(date +%s%N | cut -b1-13)
  • %s for seconds since the UNIX epoch
  • %N adding nanosecond portion
  • cut 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
  1. Get the absolute timestamp at the beginning of the program
  2. Get the absolute timestamp at the end of the program
  3. Subtract end - beginning to get the duration
  4. 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

LINKS

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com