比较两个timespec值以查看最先发生的事情的最佳方法是什么?
以下是否有任何问题?
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;
}
答案 0 :(得分:4)
您可以采用的另一种方法是为operator <()
定义全局timespec
。然后你就可以比较一下,如果有一次发生在另一次之前。
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;
}
然后在你的代码中你可以有
timespec start, end;
//get start and end populated
if (start < end)
cout << "start is smaller";