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
/$ date +%s%N
/$ $(date +%s%N | cut -b1-13)
  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)


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




Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at with a passion for cloud infrastructure/terraform/python/docs. More at