Skip to content
Advertisement

Where to find the source code of timespec_get?

The C11 standard provides the function timespec_get. If I run the example code on cppreference, or on my computer, it works:

JavaScript

However, if I look at the sources of glibc here, the code is the following:

JavaScript

Which… should not work…

Which leads to the question: where is the source code of timespec_get that is actually called?

Advertisement

Answer

The timespec_get function’s implementation depends on the system the library is running on, so it appears both as a stub in time/timespec_get.c (in case no implementation is available) and as various system-dependent implementations elsewhere.

You can see the Linux implementation in sysdeps/unix/sysv/linux/timespec_get.c,

JavaScript

This is is just a thin wrapper around a vDSO call, and the vDSO is part of the Linux kernel itself. If you are curious, look for the definition of clock_gettime there. It’s unusual that clock_gettime is in the vDSO, only a small number of syscalls are implemented this way.

Here is the x86 implementation for CLOCK_REALTIME, found in arch/x86/entry/vdso/vclock_gettime.c:

JavaScript

Basically, there is some memory in your process which is updated by the kernel, and some registers in your CPU which track the passage of time (or something provided by your hypervisor). The memory in your process is used to translate the value of these CPU registers into the wall clock time. You have to read these in a loop because they can change while you are reading them… the loop logic detects the case when you get a bad read, and tries again.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement