Search code examples
c++timestamp32-bitmilliseconds

How to get a time difference in milliseconds in a cross platform c++ 32-bit system?


I'm developing a c++ app for a cross platform 32 bit embedded system(windows and linux). For one needed functionality I need to calculate a time difference in milliseconds. Firstly the biggest precision that epoch timestamp give for 32bit systems, is that of a second. The majority of relevant answers that I came across are either 64bit related like the use of std::clock or std::chrono like:

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

Or system sprecific using

#include <sys/time.h>  

or the GetSystemTime function on windows. I also checked the poco related time functions but they are also based on using 64bit variables. Can this be done with an existing standard or external c++ library or should I follow different approach?


Solution

  • Here's a C++11 way to get epoch time and time difference in milliseconds (well, std::literals is C++14 but you don't have to use that):

    #include <iostream>
    #include <chrono>
    
    using namespace std::literals;
    
    int main()
    {
        using Clock = std::chrono::system_clock;
        auto point1 = Clock::now();
        int64_t epoch = point1.time_since_epoch() / 1ms;
        std::cout << "Time since epoch: " << epoch << std::endl;
        auto point2 = Clock::now();
        std::cout << "Time difference in milliseconds: " << ((point2 - point1) / 1ms) << std::endl;
        std::cout << "Time difference in nanoseconds: " << ((point2 - point1) / 1ns) << std::endl;
    }
    

    system_clock demo

    Time since epoch: 1486930917677
    Time difference in milliseconds: 0
    Time difference in nanoseconds: 102000
    

    For high resolution time point differences the standard has chrono::high_resolution_clock, which may offer higher precision than chrono::system_clock, but the epoch of it often starts at system boot time, not at 1-1-1970.

    high_resolution_clock demo

    Time since "epoch": 179272927
    Time difference in milliseconds: 0
    Time difference in nanoseconds: 74980
    

    Keep in mind that high_resolution_clock still has 1 second precision on Visual Studio before 2015. It has 100ns precision in Visual Studio 2015+, and should have at least 1ms precision on other platforms.

    PS std::chrono works exactly the same on 32-bit and 64-bit systems.