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;
}
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With