samedi 27 décembre 2014

Weird result with std::chrono::duration_cast for 1 second and 2 second

I am running a simple program where, I take a time_point with system_clock::now then this_thread::sleep_for(seconds(1)) and again a time_point with system_clock::now.


Now if I add some extra duration to the 1st time_point, it gives exactly the same result for 1 and 2 seconds!


Here is the demo code:



#include<iostream>
#include<chrono>
#include<thread>
using namespace std;

void CheckDuration (std::chrono::duration<int> seconds)
{
auto start = std::chrono::system_clock::now() + seconds;
std::this_thread::sleep_for(std::chrono::seconds(1));
auto stop = std::chrono::system_clock::now();

cout << "Difference = " << std::chrono::duration_cast<std::chrono::seconds>(stop-start).count() << endl;
}

int main ()
{
CheckDuration(std::chrono::duration<int>(0)); // Difference = 1
CheckDuration(std::chrono::duration<int>(1)); // Difference = 0
CheckDuration(std::chrono::duration<int>(2)); // Difference = 0 <=== ???
CheckDuration(std::chrono::duration<int>(3)); // Difference = -1
}

Aucun commentaire:

Enregistrer un commentaire