Re: How do get elapsed time in milliseconds in a shell script?

From: Frank Leonhardt <freebsd-doc_at_fjl.co.uk>
Date: Tue, 19 Jul 2022 14:08:12 UTC
On 18/07/2022 14:45, Tom Browder wrote:
>
>
> On Tue, Jul 12, 2022 at 03:09 Frank Leonhardt <freebsd-doc@fjl.co.uk> 
> wrote:
>
>     I thought this would be easy, but it's not!
>
>     I can get the time since the epoch to the nearest second (date
>     +%s), but
>     nothing more accurate. This was probably good enough in the 1970s
>     but I
>     think it's reasonable to want a better resolution even in a shell
>     script.
>
>
> I’m a wannabe FreeBSD user lurking here. Can you tell us more about 
> your use case?
>
> (Spoiler alert:  I’m a long time Unix/Linux user who now relies mostly 
> on Raku for other than very simple bash scripts.)
>
There is no use case here, other than trying to figure out a truly 
portable way of getting a high resolution tick count.

Unix isn't a real-time OS. When it was written, one second was a pretty 
short unit of time, and the smallest unit handled in many cases (e.g. 
sleep, date and the strftime() subroutine). With Unix computers now 
10,000 times faster, where one second resolution was adequate in the 
past, something a bit higher would make sense now. It seems like there 
isn't a clean way to do it using the widely supported Bourne shell (of 
which bash is a clone with backward compatibility). I was hoping there 
was a trick I wasn't aware of, but it seems not.

Linux has an extra strftime() macro %N (IIRC) that somehow gets the 
fractions of a second, although it's hard to see how as the input is a 
Unix time_t (i.e. one second resolution). As Steve O'Hara-Smith 
<steve@sohara.org> pointed out, there's a FreeBSD-specific tick count 
available as a kernel state variable, which allows a solution but 
requires conditional code in the script.

Newer versions of BSD have a replacement function called gettimeofday(), 
that passes a timeval structure containing a time_t and the time into 
the current second to microsecond resolution. Before that there was an 
ftime() library routine  from about Unix Version 7, which used a timeb 
structure that  included milliseconds instead (16-bit, see?). I'm pretty 
sure Linux supports gettimeofday() too.

So - if you're writing in 'C' you can get good resolution; if you're 
using a shell script it seems like you're out of luck if you want 
something portable. Unless there is a trick we've all missed.

Regards, Frank.