如果未设置clock_settime,clock_gettime() 是否有效?

Does clock_gettime() work if clock_settime has not been set?

本文关键字:clock 是否 有效 设置 settime 如果 gettime      更新时间:2023-10-16

如果时钟没有被clock_settime()设置,clock_gettime()是否有效?我遇到重复调用 clock_gettime() 返回相同时间值(秒)的情况。我似乎记得我需要先用 clock_settime() 设置时间。clock_gettime() 和 time() 是否使用相同的时间源?

clock_gettime(clockid_t clk_id, struct timespec *tp) - All  implementations  support  the system-wide real-time clock, which is identified by CLOCK_REALTIME.  Its time represents seconds and nanoseconds SINCE THE EPOCH.  When its time is changed, timers for a  relative  interval  are  unaffected,  but timers for an absolute point in time are affected.
time() - returns the time as the number of seconds SINCE THE EPOCH, 1970-01-01 00:00:00 +0000 (UTC).

代码是C,平台是Ubuntu 18.04。C++在这个问题中被标记,因为据我所知,C++没有提供获得高精度时间的方法(尽管 C++20 提供了),我将创建我的代码的C++版本。

clock_settime设置整个计算机的时间。 只有系统管理工具(例如GNOME控制中心)和时间同步守护进程(例如ntpd)才需要调用它。 它需要超级用户权限;大多数程序无法成功调用它。

如果从未在特定计算机上调用过clock_settime(或执行相同工作的旧 API 之一),则与当前时间的某些权威源相比,clock_gettime返回的值很可能是错误的。 但是,无论时间是否准确,时钟都应该仍在运行。 我不知道在 Linux 或其他设备上有任何 API 可以停止系统时钟。

但是,根据您使用的时钟 ID,从对clock_gettime的两次连续调用中获得相同的值可能是正常的(不是错误或问题)。 例如,如果两个调用之间的间隔短于时钟的分辨率,则可能会发生这种情况,如clock_getres报告的那样。