Search code examples
c++c++20c++-chrono

Idiomatic way to check std::chrono duration is less than 0


I know I can do this

if (timeLeft.count() < 0)

But I wonder what is the best way since I could also do:

if (timeLeft<std::chrono::seconds(0)) // or milliseconds or nanonseconds...

note: I assume both checks are the same, but I am not a chrono expert.

edit:full example:

#include<chrono>
int main(){
    const std::chrono::nanoseconds timeLeft(-5);
    if(timeLeft<std::chrono::seconds(0)){
        return 47;
    }
}

edit2: potential problem with std::chrono::seconds(0) is that novice programmer might assume it involves rounding although it does not.


Solution

  • One of the ways to express this is by using std::chrono::duration literals (https://en.cppreference.com/w/cpp/chrono/duration). It's short and clean:

    #include<chrono>
    
    int main(){
        using namespace std::chrono_literals;
        
        const auto timeLeft = -5ns;
        if(timeLeft<0s){
            return 47;
        }
    }