User
User

Reputation: 1236

C++ chrono Difference between 2 time clocks in seconds

I want to find the difference between 2 time clocks using chrono library in seconds. I tried various ways, Following is one among them. All of them works fine till the difference is 59 seconds but times out after that. I really need the actual value of difference even if it is more than 59 seconds

#include <iostream>     
#include <chrono>       
#include <thread>                        

int main ()
{
    using std::chrono::system_clock;
   using std::chrono::milliseconds;
   using std::chrono::seconds;
   using std::chrono::duration_cast;
   const auto duration = milliseconds(1000);
   const auto start = system_clock::now();

   for(int i=0; i<65; i++)
   {
       std::this_thread::sleep_for(duration);
   const auto stop = system_clock::now();

   const auto difference = std::chrono::duration_cast<seconds>(stop - start).count();

   std::cout << "Difference is =>" << difference << std::endl;

   }
}

The above outputs the difference till 59 and times out after that. Whats going on wrong here?

Upvotes: 2

Views: 4152

Answers (1)

Christophe
Christophe

Reputation: 73366

This code works fine: I could compile and execute it succesfully on macOs with Xcode and on Wingdows with MSVC2017, getting timings until 65 as expected.

Durations in seconds are not limited to 60 by std::chrono. std::chrono::seconds are just a unit of measure. You can even find out the maximum number of seconds that could be counted this way. Of course, there are system dependent limits, but these are far above 60:

std::cout << "Max is " 
    << std::chrono::duration_cast<seconds>(start-start).max().count() << std::endl;

I also get the expected result ideone (online demo), with timings between 60 and 65. But ideone has an execution time limit of around 10 seconds so that it first timed out. So I had to adjust your code by substracting 55 seconds from the start time:

const auto start = system_clock::now()-milliseconds(55000);

There's no reason for your code to fail, except a compiler/library dependent bug.

Upvotes: 3

Related Questions