HomeFreeBSD

time(3): Increase precision of time conversion functions by using gcd.

Description

time(3): Increase precision of time conversion functions by using gcd.

When converting times to and from units which have many leading zeros,
it pays off to compute the greatest common divisor first, and then do the
scaling product. This way all time unit conversion comes down to scaling a
signed or unsigned 64-bit value by a fraction represented by two signed
or unsigned 32-bit integers.

SBT_1S is defined as 2^32 . When scaling using powers of 10 above 1,
the gcd of SBT_1S and 10^N is always greater than or equal to 4,
when N is greater or equal to 2.

Scaling a sbt value to milliseconds is then done by multiplying by
(1000 / 8) and dividing by (2^32 / 8).

This trick allows for higher precision at very little additional CPU cost.

It shall also be noted that the Xtosbt() functions prior to this patch,
sometimes were off-by-one:

For example when converting 1 / 8 of a second to sbt as 125ms the old sbt
conversion function would compute 0x20000001 while the new function computes
0x20000000 which multiplied by 8 becomes SBT_1S, which is the correct value.

Reviewed by: kib@
Differential Revision: https://reviews.freebsd.org/D36857
MFC after: 1 week
Sponsored by: NVIDIA Networking