简体   繁体   English

std::chrono::system_clock + now() 到毫秒并返回不同的行为

[英]std::chrono::system_clock + now() to milliseconds and back different behavior

I'm a bit puzzled to find a portable way to convert milliseconds to std::chrono::system_time::time_point .我对找到一种将毫秒转换为std::chrono::system_time::time_point的便携方法感到有些困惑。 I looks like the code:我看起来像代码:

https://godbolt.org/z/e7Pr3oxMT https://godbolt.org/z/e7Pr3oxMT

#include <chrono>
#include <iostream>

int main ()
{
    auto now = std::chrono::system_clock::now();
    auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);

    auto value = now_ms.time_since_epoch();
    long duration = value.count();

    std::cout << duration << std::endl;

    std::chrono::milliseconds dur(duration);

    std::chrono::time_point<std::chrono::system_clock> dt(dur);

    if (dt != now_ms)
        std::cout << "Failure." << std::endl;
    else
        std::cout << "Success." << std::endl;
    

    return 0;
}

should work the same on win32 and linux.应该在 win32 和 linux 上工作相同。 But unfortunately on windows (msvc) I'm getting Failure as output.但不幸的是,在 windows (msvc) 上,我遇到了 output Failure Please, assist to understand what is wrong?请帮助理解什么是错的?

The problem is probably问题大概是

long duration = value.count();

The type long isn't necessarily 64 bits. long类型不一定是 64 位。 The standards does not define the exact size of integer types besides char .除了char之外,标准没有定义 integer 类型的确切大小。 Visual Studio uses 32 bits for long even in an x64 build, for example.例如,即使在 x64 构建中,Visual Studio 也长期使用 32 位。

Anyway, try不管怎样,试试

uint64_t duration = value.count();

in your code or just在您的代码中或只是

auto duration = value.count();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM