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

标签 c++ c linux time real-time-clock

如果时钟尚未由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 Control Center )和时间同步守护进程(例如 ntpd )才需要调用它。它需要 super 用户权限;大多数程序无法成功调用它。

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

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

关于c++ - 如果未设置clock_settime,clock_gettime() 是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55693700/

相关文章:

c++ - 方便的断言检查策略

c++ - 在 C++ 中使用嵌套循环求解一阶联立方程

linux - 如何计算列的平均值

linux - 安装 Ubuntu Linux 和通用 USB 安装程序不显示要安装的磁盘

linux - 在 Linux 中连接加密网络时如何从 nmcli 传递密码?

c++ - 如何使用 OpenCV 中可用的压缩算法?

c++ - OpenGl 2d 缩放(使用缩放和平移而不是 glOrtho)

c++ - 我应该并行化哪些循环,外部循环还是内部循环

c - exit(1) 没有给我 1 作为退出值?

c - C 中的 Strcpy 输出