time measurement

Adrian Bocaniciu a.bocaniciu at computer.org
Tue May 3 12:19:11 PDT 2005

    Hi John,

    in both FreeBSD and DragonFly "gettimeofday" is implemented via
"microtime" and "clock_gettime" is implemented via "nanotime".  Thus
even if in FreeBSD you cannot schedule events with a better resolution
than the clock interrupt period, you can at least measure the time
accurately.  In DF it should become possible eventually to also schedule
events with high resolution, but I did not look at the sources lately,
so I do not know if any work has already been done to export this
facility to the userland.

    Matt suggested "gettimeofday", but I recommend against it.  The
legacy BSD "gettimeofday" function has been obsoleted by the POSIX
"clock_gettime" function a very long time ago.  For new programs, only
"clock_gettime" should be used. 

    The are two reasons for this, one is that when the kernel uses
either the ACPI PM timer or the HPET timer for time keeping, the
resolution is better but "gettimeofday" cannot take advantage of that. 
The second reason is that even when the ancient 8254 timer is used,
"clock_gettime" gives more accurate results, because "nanotime" uses
more bits for representing the clock period than "microtime" uses, so
that the value returned by it accumulates a smaller error between two
function invocations.

    The same rule is true for all legacy BSD functions with microsecond
resolution, they should always be replaced by the equivalent POSIX
functions with nanosecond resolution, e.g. "usleep" shall be replaced by
"nanosleep" and so on.  A special case is the legacy BSD "select", where
FreeBSD & DF do not implement the corresponding POSIX "pselect", but
they implement the much better "kevent", which shall be used instead of

    Best regards !

More information about the Users mailing list