Comparing timespec values

12.7k views Asked by At

What's the best way to compare two timespec values to see which happened first?

Is there anything wrong with the following?

bool BThenA(timespec a, timespec b) {
    //Returns true if b happened first -- b will be "lower".
    if (a.tv_sec == b.tv_sec)
        return a.tv_nsec > b.tv_nsec;
    else
        return a.tv_sec > b.tv_sec;
}
1

There are 1 answers

3
NathanOliver On

Another way you can go this is to have a global operator <() defined for timespec. Then you can just you that to compare if one time happened before another.

bool operator <(const timespec& lhs, const timespec& rhs)
{
    if (lhs.tv_sec == rhs.tv_sec)
        return lhs.tv_nsec < rhs.tv_nsec;
    else
        return lhs.tv_sec < rhs.tv_sec;
}

Then in you code you can have

timespec start, end;
//get start and end populated
if (start < end)
   cout << "start is smaller";