Search code examples
c++c++-chrono

What is the std::chrono::time_point equivalent of std::numeric_limits::infinity()?


Suppose I want to call my_func() periodically at CALL_PERIOD intervals

auto last_call_time = CHRONO_NEGATIVE_INFINITY;
while (true)
{
    if (std::chrono::system_clock::now() - last_call_time > CALL_PERIOD)
    {
        last_call_time = std::chrono::system_clock::now();
        my_func();
    }
}

What would be an appropriate CHRONO_NEGATIVE_INFINITY such that the line

std::chrono::system_clock::now() - last_call_time > CALL_PERIOD

will always evaluate true on the first run?

I've tried time_point::min() but that doesn't seem to work


Solution

  • One of the main reasons to have a type like std::optional is so that we don't have to have hacks like picking a specific value to mean "not a value":

    std::optional<std::chrono::system_clock::time_point> last_call_time;
    while (true)
    {
        auto curr = std::chrono::system_clock::now()
        if (!last_call_time || (curr - *last_call_time) > CALL_PERIOD)
        {
            last_call_time = std::chrono::system_clock::now();
            my_func();
        }
    }
    

    If C++17 is not available to you, and/or you're just dead-set on using the old hack of picking a special value, you can get the clock's rep type and compute the minimum possible integer of it:

    using sys_clock = std::chrono::system_clock;
    constexpr auto min_int = std::numeric_limits<sys_clock::rep>::min();
    constexpr sys_clock::duration min_duration(min_int);
    sys_clock::time_point min_time(min_duration);
    

    Of course, min_time is still a valid time, so it's unlike any "infinity" representation for floats.