How to measure elapsed time in Bash

This article will introduce how to masure the execution time or elapsed time in Bash.

1. How to measure elapsed time

Before executing any work, save the start time and measure the time after the work is complete to calculate the execution time.

The following example measures how long it takes to sleep for 2.5 seconds. The $s of date means Unix time and outputs in seconds. %N outputs Nano seconds. That is, $s.%N returns time in Nano units. bc is used to calculate the time.

#!/bin/bash

start=`date +%s.%N`

# run something...
sleep 2.5

finish=`date +%s.%N`
diff=$( echo "$finish - $start" | bc -l )

echo 'start:' $start
echo 'finish:' $finish
echo 'diff:' $diff

Output:

$ bash example.sh
start: 1645709150.065912157
finish: 1645709152.569702381
diff: 2.503790224
codechachaCopyright ©2019 codechacha