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
{ time -p ./actual_script_runs_here ; } |& grep real | cut -d ' ' -f2
– Arkadiusz Drabczyk Sep 09 '19 at 17:03