Search code examples
linuxtimeposixreal-time

Reliably find offset between two clocks on the same machine


The Linux man page for clock_gettime(2) does a good job of explaining the difference in meaning between CLOCK_REALTIME and CLOCK_MONOTONIC. At any given time these two clocks will be offset by some varying offset. I want to keep track of this offset. A simple approximation would be

struct timespec rtime, mtime;
clock_gettime(CLOCK_REALTIME, &rtime);   
clock_gettime(CLOCK_MONOTONIC, &mtime);
// subtract the timespecs here.

But there is an unpredictable delay between the two calls. Can the kernel give me a reliable estimate of the offset in a single "atomic" operation?

BTW: I think the OP in Starting point for CLOCK_MONOTONIC wanted the same information. But the responders there seemed to be answering a different question, so I thought I would ask it in my own words.


Solution

  • adjtimex will return information regarding the state of how the system clock varies with respect to prior adjtime calls. This might not be exactly what you asked for but it might give you enough or equivalent information for whatever your needs are.