c ++无法将chrono :: duration添加到chrono :: time_point

时间:2013-08-17 00:50:31

标签: c++11 chrono

我有这个测试代码:

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

namespace chrono = std::chrono;

int main()
{
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);

    printf("time %ld.%09ld\n", ts.tv_sec, ts.tv_nsec);

    chrono::time_point<chrono::high_resolution_clock> t(chrono::seconds(ts.tv_sec));
    t += chrono::nanoseconds(ts.tv_nsec);

    chrono::seconds secs = chrono::duration_cast<chrono::seconds>(t.time_since_epoch());
    chrono::nanoseconds nsecs = chrono::duration_cast<chrono::nanoseconds>(t.time_since_epoch() - secs);

    printf("time %ld.%09ld\n", secs.count(), nsecs.count());
}

它在带有g ++ 4.7.3的Ubuntu盒子上编译得很好,但在带有4.7.2的Debian 7盒子上我得到了这个编译输出:

/home/atip/chronotest.cpp: In function ‘int main()’:
/home/atip/chronotest.cpp:15:40: error: no match for ‘operator+=’ in ‘t += std::chrono::duration<long int, std::ratio<1l, 1000000000l> >((*(const long int*)(& ts.timespec::tv_nsec)))’
/home/atip/chronotest.cpp:15:40: note: candidate is:
In file included from /home/atip/chronotest.cpp:3:0:
/usr/include/c++/4.7/chrono:550:2: note: std::chrono::time_point<_Clock, _Dur>& std::chrono::time_point<_Clock, _Dur>::operator+=(const duration&) [with _Clock = std::chrono::system_clock; _Dur = std::chrono::duration<long int, std::ratio<1l, 1000000l> >; std::chrono::time_point<_Clock, _Dur> = std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000l> > >; std::chrono::time_point<_Clock, _Dur>::duration = std::chrono::duration<long int, std::ratio<1l, 1000000l> >]
/usr/include/c++/4.7/chrono:550:2: note:   no known conversion for argument 1 from ‘std::chrono::nanoseconds {aka std::chrono::duration<long int, std::ratio<1l, 1000000000l> >}’ to ‘const duration& {aka const std::chrono::duration<long int, std::ratio<1l, 1000000l> >&}’

不确定如何解读,我如何才能解决这两个问题?最终我有一个获取timespec的函数,我想将其转换为chrono :: time_point,然后将其转换回来。

1 个答案:

答案 0 :(得分:3)

假设两种实现都符合要求。

显然,在Ubuntu上,high_resolution_clock的分辨率为nanoseconds或更精细,但在Debian 7上,high_resolution_clock的分辨率比nanoseconds更准确。编译时错误可以防止您意外截断算术:

t += chrono::nanoseconds(ts.tv_nsec);

无法准确表示nanoseconds的内容。

如果需要,可以根据需要特别请求截断,以解决此问题:

t += chrono::duration_cast<chrono::high_resolution_clock::duration>(chrono::nanoseconds(ts.tv_nsec));

这将截断为零。或者,您可以选择其他舍入模式,但您需要自己实现它们。 Herechrono::duration的舍入到偶数算法的示例(搜索&#34; round&#34;)。