CLOCK_REALTIME and CLOCK_MONOTONIC with a single call

Viewed 102

I use clock_gettime(CLOCK_MONOTONIC, &tsp1) and clock_gettime(CLOCK_REALTIME, &tsp2), one after another. Can I do it with a single call to reduce the difference?

1 Answers

There's no standard, portable way to do this - clock_gettime is based on operating system functionality that doesn't support this sort of "multi-query". Extending this functionality is non-trivial - and might require developing a driver that will expose this functionality for you.


Specifically on Linux, this might be relatively easy and does not require writing a driver.

On Linux, clock_gettime doesn't actually call into the kernel - it makes use of vdso which allows the kernel to expose information to user-space without having to switch to kernel mode. The classic example of this usage is functions like gettimeofday and clock_gettime - these aren't privileged functions (with the exception of CLOCK_REALTIME, which does require some privileges) and the information can be made available to userspace for efficiency purposes.

You can leverage vdso to access the data directly yourself - have a look at functions in /lib/vdso/gettimeofday.c - which access the tables exposed to vdso to fetch the current time. I linked specifically to do_hres which seems to be the function that accesses the timestamps directly.

By accessing the vdso tables yourself you are minimizing overhead and reducing the difference between your two calls.

Related