Search code examples
c++c++-chrono

Comparing a time point with a difference of time points


How does one go about comparing the time point t with elapsed which is difference between two time points? In other words, I am verifying whether time elapsed so far is <= the given time point i.e 100ms.

Shouldn't elapsed be a time point itself and comparing with t be no issue?

#include <chrono>
#include <thread>

using Clock = std::chrono::steady_clock;
using TimePoint = std::chrono::time_point<Clock>;

int main() 
{
    TimePoint begin = Clock::now();

    std::chrono::seconds delay(2);
    std::this_thread::sleep_for(delay);
    
    auto cur = Clock::now();
    auto elapsed = cur - begin;

    TimePoint t = TimePoint(std::chrono::milliseconds(100));

    if (elapsed <= t)
    {
        
    }
}

Solution

  • The difference between 2 time_points is not a std::chrono::time_point but rather a std::chrono::duration, which represents a time interval.

    Therefore you need to change this line:

    TimePoint t = TimePoint(std::chrono::milliseconds(100));
    

    Into:

    std::chrono::duration t = std::chrono::milliseconds(100);
    

    Or simply use auto so that the compiler will infer this type:

    auto t = std::chrono::milliseconds(100);