Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing timespec values

Tags:

c++

linux

gnu

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;
}
like image 576
Pat Flegit Avatar asked Jun 17 '15 15:06

Pat Flegit


1 Answers

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";
like image 73
NathanOliver Avatar answered Sep 21 '22 01:09

NathanOliver