【发布时间】:2018-02-16 02:22:10
【问题描述】:
我编写了一个简单的程序来确定我是否可以在我的系统上获得纳秒精度,这是一个 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 系统的正常运行时间。两个时钟似乎都具有微秒精度(999848ns ≅ 1ms),尽管MONOTONIC 以纳秒为单位输出,这令人困惑。
man clock_gettime 状态:
CLOCK_REALTIME_HR 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 产生微秒。
【问题讨论】:
-
在 Linux 中你很难得到微秒级的精度,绝对不是纳秒级!也许你混淆了精度和分辨率? 非常不同的东西!这闻起来很像 XY 问题。为什么要获得 ns 分辨率?
-
精确很容易,准确则不然。
-
'我可以在这个系统中获得以纳秒为单位的本地时间吗?'在系统的什么地方?移动这样的值(例如,从内核调用中返回它)会使它变得陈旧。
-
@Olaf 我正在检查是否可以满足业务需求(无需深入研究硬实时系统)并超越。时间戳等
-
@MartinJames 点了。在这种情况下,只要延迟相同,应该没有问题。