A simple question: do time(...) and clock_gettime( CLOCK_REALTIME, ... ) produce the same time theoretically (in respect to seconds only)?
Here's what I mean:
time_t epoch;
time( &epoch );
and
struct timespec spec;
clock_gettime( CLOCK_REALTIME, &spec );
Are these two supposed to return exactly the same result (in respect to seconds)?
I "tested" this with changing time and time zones and epoch and spec.tv_sec always show the same result, but the documentation of CLOCK_REATIME confuses me a bit and I'm not sure, that they will always be the same.
Real world situation: I have a piece of code, which uses time. Now I want to have the time in milliseconds (which can be taken from spec.tv_nsec, multiplied by 1000000). So I think about removing time and using directly clock_gettime, but I'm not sure if this will remain the same in all situations.
The question is somehow related to Measure time in Linux - time vs clock vs getrusage vs clock_gettime vs gettimeofday vs timespec_get? but the information there was not enough for me.. I think.
[Note: I used the git master branch and v4.7 for the reference links below, x86 only, as I'm lazy.]
time() is in fact an alias for the equally named syscall, which calls get_seconds, happens at kernel/time/time.c. That syscall uses the get_seconds function to return the UNIX timestamp, which is read from the core timekeeping struct, more precisely from the "Current CLOCK_REALTIME time in seconds" field (xtime_sec).
clock_gettime() is a glibc function in sysdeps\unix\clock_gettime.c, which simply calls gettimeofday if the supplied clock ID is CLOCK_REALTIME, which is again backed by the equally named syscall (source is in the same time.c file, above). This one calls do_gettimeofday, which eventually ends up calling __getnstimeofday64, that queries... the very same xtime_sec field from the same struct as above.
Update:
As @MaximEgorushkin cleverly pointed out, a new vDSO mechanism hijacks (a good sign it is present, if your binary depends on linux-vdso.so.*) the clock_gettime call and redirects it to __vdso_clock_gettime. This one uses a new clock source management framework (gtod - Generic Time Of Day). A call to do_realtime, and it reads from a structure, struct vsyscall_gtod_data's wall_time_sec field. This structure is maintained by update_vsyscall, from the same timekeeper struct as the above.
The answer is: yes, they get the time from the same clock source.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With