Search code examples
c++clinuxtimereal-time-clock

Does clock_gettime() work if clock_settime has not been set?


Does clock_gettime() work if the clock has NOT been set by clock_settime()? I have a situation where repeated calls to clock_gettime() returns the same time value (seconds). I seem to remember that I needed to first set the time with clock_settime(). Also do clock_gettime() and time() use the same time source?

clock_gettime(clockid_t clk_id, struct timespec *tp) - All  implementations  support  the system-wide real-time clock, which is identified by CLOCK_REALTIME.  Its time represents seconds and nanoseconds SINCE THE EPOCH.  When its time is changed, timers for a  relative  interval  are  unaffected,  but timers for an absolute point in time are affected.

time() - returns the time as the number of seconds SINCE THE EPOCH, 1970-01-01 00:00:00 +0000 (UTC).

Code is C, platform is Ubuntu 18.04. C++ is tagged in this question, because as far as I know C++ does not provide an method of obtaining high precision time (though C++20 does), and I will create a C++ version of my code.


Solution

  • clock_settime sets the time for the entire computer. Only system administration tools (e.g. the GNOME Control Center) and time synchronization daemons (e.g. ntpd) should ever need to call it. It requires superuser privileges; most programs cannot successfully call it.

    If clock_settime (or one of the older APIs that do the same job) has never been called on a particular computer, the values returned by clock_gettime may well be wrong by comparison to some authoritative source of the current time. However, the clocks should all still be running, whether or not the time is accurate. I'm not aware of any API, on Linux or otherwise, to stop the system clock.

    However however, depending which clock ID you're using, getting the same value from two consecutive calls to clock_gettime may be normal (not a bug or a problem). For instance, this may happen if the interval between the two calls is shorter than the resolution of the clock, as reported by clock_getres.