Bash Shell – Calculate Time Difference Between Two Dates

bashshell

I've this silly script to track execution time of my cron jobs to know when script started and stopped.

start=$(date +'%Y-%m-%d %H:%M:%S') # This line converts to 2019-09-10 00:50:48
echo "$start"

./actual_script_runs_here

stop=$(date +'%Y-%m-%d %H:%M:%S')
echo "$stop"

This method works. But I've to calculate time it took to run the script by myself. Is it possible to calculate this in bash?

Or I could use time command. But it returns 3 different times with 3 new lines. I'd prefer to see that time result in one line together with my script result.

Best Answer

You could use date +%s to get a date format that you can easily do math on (number of seconds [with caveats] since Jan 1 1970 00:00:00Z). You can also convert your ISO-format date back (possibly incorrectly, due to issues like daylight saving time) using date -d "$start" +%s. It's not ideal not only due to DST issues when converting back, but also if someone changes the time while your program is running, or if something like ntp does, then you'll get a wrong answer. Possibly a very wrong one.

A leap second would give you a slightly wrong answer (off by a second).

Unfortunately, checking time's source code, it appears time suffers from the same problems of using wall-clock time (instead of "monotonic" time). Thankfully, Perl is available almost everywhere, and can access the monotonic timers:

start=$(perl -MTime::HiRes=clock_gettime,CLOCK_MONOTONIC -E 'say clock_gettime(CLOCK_MONOTONIC)')

That will get a number of seconds since an arbitrary point in the past (on Linux, since boot, excluding time the machine was suspended). It will count seconds, even if the clock is changed. Since it's somewhat difficult to deal with real numbers (non-integers) in shell, you could do the whole thing in Perl:

#!/usr/bin/perl
use warnings qw(all);
use strict;

use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);

my $cmd   = $ARGV[0];
my $start = clock_gettime(CLOCK_MONOTONIC);

system $cmd @ARGV; # this syntax avoids passing it to "sh -c"

my $exit_code = $?;
my $end       = clock_gettime(CLOCK_MONOTONIC);
printf STDERR "%f\n", $end - $start;

exit($exit_code ? 127 : 0);

I named that "monotonic-time"; and it's used just like "time" (without any arguments of its own). So:

$ monotonic-time sleep 5
5.001831                 # appeared ≈5s later
$ monotonic-time fortune -s
Good news is just life's way of keeping you off balance.
0.017800
Related Question