Issue
When given two bash commands command1
and command2
how do you measure the difference in execution time? Ideally, I want this to be directional and not in absolute. Millisecond accuracy is preferred.
I can achieve this by code, but the way I do it feels very cumbersome in comparison.
#!/bin/env bash
command1=$1
command2=$2
time1=$(/usr/bin/time -f "%E" $command1 2>&1 >/dev/null |\
awk -F: '{secs=$3; secs+=$2*60; sec+=$3*3600; printf "%.3f\n", secs*1000}')
time2=$(/usr/bin/time -f "%E" $command2 2>&1 >/dev/null |\
awk -F: '{secs=$3; secs+=$2*60; sec+=$3*3600; printf "%.3f\n", secs*1000}')
time_diff=$(echo "$time1 - $time2" | bc)
echo $time_diff
Solution
Why not just:
start=$(date +%s.%N)
command1
mid=$(date +%s.%N)
command2
stop=$(date +%s.%N)
time_diff=$(bc -l <<<"($mid - $start) - ($stop - $mid)")
echo "$time_diff"
or yet better
start=$EPOCHREALTIME
command1
mid=$EPOCHREALTIME
command2
stop=$EPOCHREALTIME
time_diff=$(bc -l <<<"($mid - $start) - ($stop - $mid)")
echo "$time_diff"
Answered By - KamilCuk Answer Checked By - Senaida (WPSolving Volunteer)