Pat Flegit
Pat Flegit

Reputation: 183

Comparing timespec values

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;
}

Upvotes: 7

Views: 13456

Answers (1)

NathanOliver
NathanOliver

Reputation: 180594

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";

Upvotes: 8

Related Questions