Search code examples
c++11c++-chrono

C++11 Generic function to compare difference between two times?


I would like to write a generic function so that I can compare two timestamps (my own class, returns nanoseconds since epoch) with whatever std::chrono::duration value (seconds, milliseconds etc) I pass in, so something like:

template<typename PERIOD>
bool IsTimestampWithin(const MyTime t1, const MyTime t2, const rsInt64 units){
    return t2.Nanos() - t1.Nanos() < units;
}

However, I am uncertain how to create an std::chrono object from the number of nanoseconds my timestamp returns. Every example I could find was using system or high precision clock casts.


Solution

  • You can duration_cast any duration to std::chrono::nanoseconds, then use .count() to extract the nanosecond value.

    using std::chrono::duration;
    using std::chrono::duration_cast;
    using std::chrono::nanoseconds;
    
    template<typename R, typename P>
    bool IsTimestampWithin(const MyTime t1, const MyTime t2, const duration<R, P>& units){
        return t2.Nanos() - t1.Nanos() < duration_cast<nanoseconds>(units).count();
    }
    
    // usage:
    
    if (isTimestampWithin(previous, now, std::chrono::milliseconds(300))) {
        ...
    }
    

    If your MyTime can be converted to a std::chrono::time_point structure (from the same clock source), then you don't even need to care about duration_cast, you could simply write:

    return t2.to_time_point() - t1.to_time_point() < units;