On linux, you can get the monotonic time with clock_gettime which is also what std::chrono::steady_clock from C++ uses.
There is also absolute time, in seconds from the unix epoch. This is called “realtime”.
If the system is time synced with ntp, monotonic time is rate adjusted to have the same rate as realtime. That means it (after ntp has converged) will run at a constant offset to realtime.
Sometimes, one need to convert between the two. An example would be if some system reports in monotonic time, but the data has to be presented with absolute time.
One way of doing this is to query monotonic and realtime to find out the offset between the two. The problem with this is that some time elapses between the two function calls, so the offset may be off by some amount. This gets worse on a loaded system where the process may be interrupted for some other process to run.
Is there another way of getting the offset? I could not find one after searching, so I came up with the method in the next section.
In linux, time is kept in an internal structure called struct timekeeper
The offset we search for is the offs_real member.
This is not possible to read directly, not even for kernel modules.
I was able to make a kernel module to read this out through a file in the /proc filesystem.
It reads the current monotonic time with ktime_get. Then it can be converted to realtime using ktime_mono_to_any, and the difference between the two is what we are after.
const ktime_t now = ktime_get();
const ktime_t now_real = ktime_mono_to_any(now, TK_OFFS_REAL);
const ktime_t diff = now_real - now;
To get the kernel module to present the diff in a file, functions
proc_create, proc_remove and
struct proc_ops are needed.
I might clean up my code and publish it later. But I wanted to write the important steps down in this article.
Why is this not already a part of the linux kernel? It could be a system call or a file in proc like I described above.