我编写了一个简单的程序来确定我是否可以在我的系统上获得纳秒精度,这是一个 RHEL 5.5 VM(内核 2.6.18-194)。
// cc -g -Wall ntime.c -o ntime -lrt
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
struct timespec spec;
printf("CLOCK_REALTIME - \"Systemwide realtime clock.\":\n");
clock_getres(CLOCK_REALTIME, &spec);
printf("\tprecision: %ldns\n", spec.tv_nsec);
clock_gettime(CLOCK_REALTIME, &spec);
printf("\tvalue : %010ld.%-ld\n", spec.tv_sec, spec.tv_nsec);
printf("CLOCK_MONOTONIC - \"Represents monotonic time. Cannot be set.\":\n");
clock_getres(CLOCK_MONOTONIC, &spec);
printf("\tprecision: %ldns\n", spec.tv_nsec);
clock_gettime(CLOCK_MONOTONIC, &spec);
printf("\tvalue : %010ld.%-ld\n", spec.tv_sec, spec.tv_nsec);
return 0;
}
示例输出:
CLOCK_REALTIME - "Systemwide realtime clock.":
precision: 999848ns
value : 1504781052.328111000
CLOCK_MONOTONIC - "Represents monotonic time. Cannot be set.":
precision: 999848ns
value : 0026159205.299686941
所以 REALTIME
给我本地时间和 MONOTONIC
系统的正常运行时间。两个时钟似乎都具有 μs 精度 (999848ns ≅ 1ms),即使 MONOTONIC
以纳秒为单位输出,这令人困惑。
man clock_gettime
指出:
CLOCK_REALTIME_HR High resolution version of CLOCK_REALTIME.
但是,grep -R CLOCK_REALTIME_HR/usr/include/| wc -l
返回 0
并尝试在 error: ‘CLOCK_REALTIME_HR’ undeclared (first use in this function)
中编译结果。
我试图确定我是否可以获得纳秒精度的本地时间,但要么我的代码有错误,要么 5.5 不完全支持此功能(或者 VM 的 HPET 已关闭,或其他原因)。
我可以在这个系统中获得以纳秒为单位的本地时间吗?我做错了什么?
编辑
嗯,答案似乎是否定的。
虽然可以达到纳秒级精度,但系统在这种情况下不能保证纳秒级精度(这里有一个明确的 answer 关于差异而不是咆哮)。典型的 COTS 硬件并不能真正处理它(另一个方向正确的 answer)。
我仍然很好奇为什么时钟报告相同的 clock_getres
分辨率,而 MONOTONIC
产生的似乎是纳秒值,而 REALTIME
产生微秒。
最佳答案
RHEL5 在这一点上真的很古老,你应该考虑升级。在较新的系统 (Ubuntu 16.04) 上,您的程序会产生:
CLOCK_REALTIME - "Systemwide realtime clock.":
precision: 1ns
value : 1504783164.686220185
CLOCK_MONOTONIC - "Represents monotonic time. Cannot be set.":
precision: 1ns
value : 0000537257.257923964
关于内核中的 CLOCK_REALTIME 纳秒精度支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46094769/