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) usingdate -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: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:
I named that "monotonic-time"; and it's used just like "time" (without any arguments of its own). So: