[plug] Elapsed time in scripts

Brad Campbell brad at fnarfbargle.com
Wed Jan 3 11:04:56 AWST 2024


G'day mobsters..

Quite often I find myself wanting to time tasks in scripts. I used to use all sorts of if/then maths to break up seconds to clock friendly formats.
I had a thought perhaps I could make date do it for me. Turns out the Epoch was a Thursday, so we need to fast forward 3 days to get a workable day count (start on day 0).

This gives elapsed time in days:hours:minutes:seconds. However it only works for tasks that run less than 7 days or the day counter wraps.

START=`date +%s`

// insert task here

END=`date +%s`
echo Task took `date -d @$((END-START+259200)) -u +%w:%H:%M:%S`

Just to point out another ugly, ugly bruteforce way I've used in the past :

# ------------ How long did the task take? ---------------
END=`date +%s`
runtime=$(($END-$START))
let days=$(($runtime/86400))
let hrt=$(($runtime%86400))
let hours=$(($hrt/3600))
let mint=$(($hrt%3600))
let minutes=$(($mint/60))
let secsd=$((mint%60))
echo Task took `printf "%.2d:%.2d:%.2d:%.2d" $days $hours $minutes $secsd`

A couple of the many, many ways to skin a cat. I like the former method, but I'm always interested to see alternatives.

Regards,
Brad


More information about the plug mailing list