1
votes

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?

1
Do you need epoch time in milliseconds or do you need a difference between two time points in milliseconds?rustyx
@RustyX I need a difference between two time points in milliseconds, but I assume if I can get epoch time in milliseconds in different time points will also do the job, unless I'm missing something.dk13
There is no standard portable way to get epoch time in milliseconds. chrono::system_clock often has 1s precision and chrono::high_resolution_clock doesn't start at epoch.rustyx
@RustyX Ok then a simple difference between two time points in milliseconds will be sufficient.dk13

1 Answers

5
votes

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.