Search code examples
c++c++-chrono

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. I looks like the code :

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. But unfortunately on windows (msvc) I'm getting Failure as output. Please, assist to understand what is wrong ?


Solution

  • The problem is probably

    long duration = value.count();
    

    The type long isn't necessarily 64 bits wide. The C++ standard does not define the exact size of integer types besides char. Visual Studio uses 32 bits for long even in an x64 build, for example.

    Anyway, try

    uint64_t duration = value.count();
    

    in your code or just

    auto duration = value.count();