timespec.tv_sec始终返回0

时间:2012-06-20 19:18:05

标签: c++ time clock

我正在学习如何使用clock_getres(网上几乎没有任何好的文档)。我的代码如下所示:

timespec now;
clock_getres(CLOCK_REALTIME,&now);
std::cout<<statut_cast<int>(now.tv_sec)<<","<<static_cast<int>(now.tv_nsec)<<std::endl;

无论何时运行此代码,输出始终为0,1 任何人都可以解释为什么这不起作用?

2 个答案:

答案 0 :(得分:6)

使用clock_gettime返回当前时间,而不是clock_getres,它返回时钟的分辨率。

http://pubs.opengroup.org/onlinepubs/009604599/functions/clock_getres.html

  

clock_getres()函数应返回任何时钟的分辨率

     

clock_gettime()函数应返回指定时钟tp的当前值clock_id

答案 1 :(得分:2)

这是正确的行为 - 输出为0,1,因为您尝试获得分辨率的时钟具有纳秒级分辨率。因此now.tv_nsec=1now.tv_sec=0。如果它没有纳秒分辨率,则输出为0,0