Search code examples
c++c++-chrono

C++ how to check if the difference of two millisecond values is positive?


I need to introduce minimum 2 seconds delay. For that I have done this:

typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds Milliseconds;
Clock::time_point t0 = Clock::now();

// DO A LOTS OF THINGS HERE.....

Clock::time_point t1 = Clock::now();
Milliseconds delayTime = Milliseconds(2000) - 
     std::chrono::duration_cast<Milliseconds>(t1 - t0); 

// Check if time left from initial 2 seconds wait the difference
if (delayTime > Milliseconds(0))
{
    std::this_thread::sleep_for(delayTime);
}

Did I check correctly if still time left?


Solution

  • Unless you really need to ensure that you don't call sleep at all if the 2 seconds has already elapsed, it seems like it would be a lot easier to compute when the sleep should end, then call sleep_until, passing that time.

    auto t1 = Clock::now() + 2s; // beware: requires C++14
    
    // do lots of things here
    
    std::this_thread::sleep_until(t1);
    

    If 2 seconds has already elapsed, the sleep_until (at least potentially) returns immediately. If it hasn't elapsed yet, the thread sleeps until the specified time.