比较timespec值

时间:2015-06-17 15:28:37

标签: c++ c linux gnu

比较两个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;
}

1 个答案:

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