clock_gettime()仍然不单调-替代方案? [英] clock_gettime() still not monotonic - alternatives?

查看:231
本文介绍了clock_gettime()仍然不单调-替代方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有一段时间了(例如,请参见此旧问题,并且当您在Google上搜索时会弹出错误报告),clock_gettime()似乎不会单调报告回时间.为了排除我可能忽略的任何愚蠢错误,以下是相关代码(摘自大型程序):

As has been known for a while (see, e.g., this old question, and bug reports that pop when you google this), clock_gettime() doesn't appear to report back time monotonically. To rule out any silly error I might have overseen, here is the relevant code (excerpt from larger program):

<include time.h>

long nano_1, nano_2;
double delta;
struct timespec tspec, *tspec_ptr;

clock_gettime(CLOCK_MONOTONIC_RAW, tspec_ptr);
nano_1 = tspec.tv_nsec;
sort_selection(sorted_ptr, n);
clock_gettime(CLOCK_MONOTONIC_RAW, tspec_ptr);
nano_2 = tspec.tv_nsec;  
delta = (nano_2 - nano_1)/1000000.0;
printf("\nSelection sort took %g micro seconds.\n", (double) delta);

排序小数组(大约1,000个元素)报告合理的时间.当我使用3种排序算法对较大的(10,000+)进行排序时,三者中的1-2会报告负的排序时间.我尝试了手册页中提到的所有时钟类型,不仅是CLOCK_MONOTONIC_RAW-没有更改.

Sorting small arrays (about 1,000 elements) reports plausible times. When I sort larger ones (10,000+) using 3 sort algorithms, 1-2 of the 3 report back negative sort time. I tried all clock types mentioned in the man page, not only CLOCK_MONOTONIC_RAW - no change.

(1)我在代码中忽略了什么?
(2)clock_gettime()是否有替代方法,可以以比秒更精确的增量来测量时间?我不需要纳秒级,但秒级太粗糙了,无法提供真正的帮助.

(1) Anything I overlooked in my code?
(2) Is there an alternative to clock_gettime() that measures time in increments more accurate than seconds? I don't need nanonseconds, but seconds is too coarse to really help.

系统:
-Ubuntu 12.04.
-内核3.2.0-30
-gcc 4.6.3.
-libc版本2.15
-用-lrt

System:
- Ubuntu 12.04.
- kernel 3.2.0-30
- gcc 4.6.3.
- libc version 2.15
- compiled with -lrt

推荐答案

这与clock_gettime的单调时钟实际上并不是单调的神话(实际上可能是有基础的,但是从来没有单调的)无关.有据可查,可能很久以前就已修复).这只是程序中的错误. tv_nsec是时间值的纳秒部分,存储为两个字段:

This has nothing to do with the mythology of clock_gettime's monotonic clock not actually being monotonic (which probably has a basis in reality, but which was never well documented and probably fixed a long time ago). It's just a bug in your program. tv_nsec is the nanoseconds portion of a time value that's stored as two fields:

  • tv_sec-整秒
  • tv_nsec-纳秒,范围从0到999999999
  • tv_sec - whole seconds
  • tv_nsec - nanoseconds in the range 0 to 999999999

当然,当tv_sec递增时,tv_nsec将从999999999向后跳至0.要计算timespec结构的差异,您需要以秒为单位的差异取1000000000倍,并将其加到以纳秒为单位的差异中.当然,如果您不先转换为64位类型,这可能很快就会溢出.

Of course tv_nsec is going to jump backwards from 999999999 to 0 when tv_sec increments. To compute differences of timespec structs, you need to take 1000000000 times the difference in seconds and add that to the difference in nanoseconds. Of course this could quickly overflow if you don't convert to a 64-bit type first.

这篇关于clock_gettime()仍然不单调-替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆