首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c++无法向chrono::time_point添加to::chrono::time_point

c++无法向chrono::time_point添加to::chrono::time_point
EN

Stack Overflow用户
提问于 2013-08-17 00:50:30
回答 1查看 3.1K关注 0票数 3

我有一个测试代码:

代码语言:javascript
复制
#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框上,我得到了这个编译输出:

代码语言:javascript
复制
/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,然后再把它转换回来。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-08-17 01:02:39

假设这两种实现是一致的。

显然,在Ubuntu上,high_resolution_clock的分辨率是nanoseconds或更精细,但在Debian 7上,high_resolution_clock的分辨率要比nanoseconds高。编译时错误防止您意外地截断算法:

代码语言:javascript
复制
t += chrono::nanoseconds(ts.tv_nsec);

nanoseconds不能被准确地表示出来。

如果需要,可以通过特别请求截断来解决这一问题:

代码语言:javascript
复制
t += chrono::duration_cast<chrono::high_resolution_clock::duration>(chrono::nanoseconds(ts.tv_nsec));

这将截断为零。或者,您可以选择其他舍入模式,尽管您需要自己实现它们。这里是一个用于chrono::duration (搜索“圆形”)的整数到偶数算法的例子。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18284045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档