mips 路由器上 clock_gettime() 的纳秒

nanoseconds from clock_gettime() on mips router

我正在尝试在 1GHz MIPS 路由器上从 CLOCK_REALTIME 获得纳秒分辨率。当我在 1GHz 虚拟机上为 x86 和 运行 编译以下代码时,我得到了纳秒分辨率。当我在 1GHz 路由器上编译 mips 和 运行 时,它似乎四舍五入到微秒。

#include <stdio.h>
#include <time.h>

int main(int argc, char **argv, char **arge) {
  struct timespec tps, tpe;
  if ((clock_gettime(CLOCK_REALTIME, &tps) != 0)
      || (clock_gettime(CLOCK_REALTIME, &tpe) != 0)) {
    perror("clock_gettime");
    return -1;
  }
  printf("%lu s, %lu ns\n", tpe.tv_sec-tps.tv_sec,
     tpe.tv_nsec-tps.tv_nsec);
  return 0;
}

以下是采样时间:

vagrant@vagrant-ubuntu-trusty-64:~$ gcc clock.c -o clock_x86 -static -lrt
vagrant@vagrant-ubuntu-trusty-64:~$ ./clock_x86
0 s, 221 ns


vagrant@vagrant-ubuntu-trusty-64:~$ mipsel-openwrt-linux-gcc clock.c -lrt -static -o clock_mips
<...scp...>
root@OpenWrt:~# ./clock_mips
0 s, 3000 ns

我对时钟、MIPS、处理器等有什么误解吗?我希望调用 CLOCK_REALTIME 产生纳秒级 granularity/resolution,而不管处理器架构如何。

此外,如果有人能阐明这些 POSIX 计时器是如何实现的以及它们是如何进行测量的,我将不胜感激。

clock_gettime 支持的最小 分辨率为纳秒。但不能保证系统时钟的分辨率(或实际上该功能的实现)会高于或低于该值。

调用clock_getres查询时钟分辨率

时钟的保证粒度在POSIX.1-2008中指定为至少20ms。这是相关的片段:

The maximum allowable resolution for CLOCK_REALTIME and CLOCK_MONOTONIC clocks and all time services based on these clocks is represented by {_POSIX_CLOCKRES_MIN} and shall be defined as 20 ms (1/50 of a second). Implementations may support smaller values of resolution for these clocks to provide finer granularity time bases. The actual resolution supported by an implementation for a specific clock is obtained using the clock_getres() function. If the actual resolution supported for a time service based on one of these clocks differs from the resolution supported for that clock, the implementation shall document this difference.

基本上,您需要调用 clock_getres() 来确定实现指定的分辨率实际上是什么。不要做任何假设它比 20 毫秒更精细的事情。