Getting and setting

The functions clock_gettime() and clock_settime() are the POSIX functions based on the kernel function ClockTime(). These functions can be used to get or set the current time of day. Unfortunately, setting this is a "hard" adjustment, meaning that whatever time you specify in the buffer is immediately taken as the current time. This can have startling consequences, especially when time appears to move "backwards" because the time was ahead of the "real" time. Generally, setting a clock using this method should be done only during power up or when the time is very much out of synchronization with the real time.

That said, to effect a gradual change in the current time, the function ClockAdjust() can be used:

int
ClockAdjust (clockid_t id,
             const struct _clockadjust *new,
             const struct _clockadjust *old);

The parameters are the clock source (always use CLOCK_REALTIME), and a new and old parameter. Both the new and old parameters are optional, and can be NULL. The old parameter simply returns the current adjustment. The operation of the clock adjustment is controlled through the new parameter, which is a pointer to a structure that contains two elements, tick_nsec_inc and tick_count. Basically, the operation of ClockAdjust() is very simple. Over the next tick_count clock ticks, the adjustment contained in tick_nsec_inc is added to the current system clock. This means that to move the time forward (to "catch up" with the real time), you'd specify a positive value for tick_nsec_inc. Note that you'd never move the time backwards! Instead, if your clock was too fast, you'd specify a small negative number to tick_nsec_inc, which would cause the current time to not advance as fast as it would. So effectively, you've slowed down the clock until it matches reality. A rule of thumb is that you shouldn't adjust the clock by more than 10% of the base timing resolution of your system (as indicated by the functions we'll talk about next, ClockPeriod() and friends).