7

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Pat Flegit
  • 183
  • 1
  • 2
  • 11

1 Answers1

8

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";
NathanOliver
  • 171,901
  • 28
  • 288
  • 402