在cout中进行算术运算时,chrono duration_cast无效

时间:2016-06-15 17:15:39

标签: c++ casting iostream chrono

我不明白以下行为

unsigned long begin_time = \
    std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();

//some code here

std::cout << "time diff with arithmetic in cout: " << \
    std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() - begin_time << std::endl;

unsigned long time_diff = \
    std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() - begin_time;

std::cout << "time_diff: " << time_diff << std::endl;

输出:

time diff with arithmetic in cout: <very large number (definitely not milliseconds)>
time_diff: <smaller number (definitely milliseconds)>

当我在cout中进行算术运算时,duration_cast为什么不起作用?我已经使用unsigned intint作为time_diff变量,但是当我在变量初始化或赋值中首次执行算术时,我总是得到良好的输出。

注意

我正在使用Visual Studio 2013(社区版)

2 个答案:

答案 0 :(得分:1)

你可能会溢出unsigned long(sizeof为4):

unsigned long begin_time = \
    std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();

推荐:

using namespace std::chrono;
auto begin_time = steady_clock::now();

//some code here

std::cout << "time diff with arithmetic in cout: " << 
    duration_cast<milliseconds>(steady_clock::now() - begin_time).count() << std::endl;

答案 1 :(得分:1)

duration_cast没有任何问题,问题是unsigned long不足以处理自纪元以来毫秒级的时间。从ideone我得到这个输出:

Max value for `unsigned long`: 4294967295
Milliseconds since epoch:     15426527488

我通过直接推出获得毫秒数:

std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() << std::endl;

在您的第一个输出中,您获得了一个巨大的数字,因为begin_time被强制转换为std::chrono::milliseconds::rep(返回类型为.count()),其大小足以处理time_since_epoch (由标准保证),而在第二个输出中,两个值都被unsigned long截断,因此您得到(可能)正确的结果。

注意:可能存在unsigned long足以处理此问题的架构,但您不应该依赖它并直接使用为std::chrono::duration提供的算术运算符。 < / p>