Monotonic clock on OSX

The Mach kernel provides access to system clocks, out of which at least one (SYSTEM_CLOCK) is advertised by the documentation as being monotonically incrementing.

#include <mach/clock.h>
#include <mach/mach.h>

clock_serv_t cclock;
mach_timespec_t mts;

host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);

mach_timespec_t has nanosecond precision. I’m not sure about the accuracy, though.

Mac OS X supports three clocks:

  • SYSTEM_CLOCK returns the time since boot time;
  • CALENDAR_CLOCK returns the UTC time since 1970-01-01;
  • REALTIME_CLOCK is deprecated and is the same as SYSTEM_CLOCK in its current implementation.

The documentation for clock_get_time says the clocks are monotonically incrementing unless someone calls clock_set_time. Calls to clock_set_time are discouraged as it could break the monotonic property of the clocks, and in fact, the current implementation returns KERN_FAILURE without doing anything.

Leave a Comment