使用clock_getres - 新手Linux C.

8 c linux

我正在尝试确定Linux机器上的计时器的粒度.根据clock_getres的手册页,我应该能够使用这个片段:

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

int main( int argc, char** argv )
{
  clockid_t types[] = { CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID, (clockid_t) - 1 };

  struct timespec spec;
  int i = 0;
  for ( i; types[i] != (clockid_t) - 1; i++ )
  {
    if ( clock_getres( types[i], &spec ) != 0 )
    {
      printf( "Timer %d not supported.\n", types[i] );
    }
    else
    {
      printf( "Timer: %d, Seconds: %ld Nanos: %ld\n", i, spec.tv_sec, spec.tv_nsec );
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试这样构建:gcc -o timertest timertest.c

这在Solaris上运行良好但在Linux上我得到错误:

/tmp/ccuqfrCK.o: In function `main':
timertest.c:(.text+0x49): undefined reference to `clock_getres'
collect2: ld returned 1 exit status

我已经尝试将-lc传递给gcc,显然clock_getres是在libc中定义的,但它没有区别.我必须在这里错过一些简单的东西 - 任何想法?

谢谢,

拉斯

Nik*_*sov 14

你需要与RT库链接(-lrt)


osg*_*sgx 5

不幸的是,clock_getres()POSIX 函数(可选的“实时”部分 - 注意POSIX 页面http://pubs.opengroup.org/onlinepubs/009695399/functions/clock_getres.html上的REALTIME标记)不会报告 Linux 中的计时器粒度。它只能返回两个预定义结果:1/HZ 表示低分辨率时钟(其中 HZ 是配置 Linux 内核时使用的 CONFIG_HZ 宏的值,典型值为 100 300 1000)或 1 ns 表示高分辨率时钟(hrtimers)。

内核中的文件有关于这种粒度和结果 linux/include/linux/hrtimer.h含义的注释http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/include/linux/hrtimer.hclock_getres()

269 /*
270  * The resolution of the clocks. The resolution value is returned in
271  * the clock_getres() system call to give application programmers an
272  * idea of the (in)accuracy of timers. Timer values are rounded up to
273  * this resolution values.
274  */
Run Code Online (Sandbox Code Playgroud)

因此,即使计时器源注册为“hrtimer”(高分辨率计时器),它也可能不是每纳秒 (ns) 计时一次。返回的值clock_getres()只会表明该计时器未舍入(因为timespec结构具有纳秒精度)。

在Linux中,POSIX API通常由glibc(或其衍生物,如eglibc)实现,默认情况下链接到所有程序(-lc链接器选项)。版本低于 2.17 的 Glibc 将 POSIX 的一些可选部分分离到其他库中,例如-lpthread-lrt. clock_getres()被定义在-lrt.

-lrtglibc 2.17 及更高版本不需要选项,根据 Linux 手册页clock_getres()clock_gettime()函数,http://man7.org/linux/man-pages/man2/clock_gettime.2.html

使用 -lrt 链接(仅适用于 2.17 之前的 glibc 版本)。

该更改也已在兼容性跟踪器中注册:http://upstream.rosalinux.ru/compat_reports/glibc/2.16.0_to_2.17/abi_compat_report.html

添加了符号... libc-2.17.so ...clock_getres