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
Related Posts
- How to measure elapsed time in Bash
- Ceil, Floor, Round off a devided number in Bash
- Check if a number is Positive or Negative in Bash
- How to Print a Variable in Bash
- Number Comparison Operators in Bash
- Convert between Uppercase and Lowercase in Bash
- Check if a File or Directory exists in Bash
- How to extract substring in Bash
- Bash Case Statement with examples
- How to use Command Line Arguments in Bash
- How to use Arrays in Bash
- How to Compare strings in Bash Shell
- if..else statement in Bash
- Add, Subtract, Multiply, Division with Numbers in Bash
- Bash For, Whlie Loop Examples
- How to Pass and Use command line arguments in Bash