比较时间规范值

Comparing timespec values

本文关键字:范值 时间 比较      更新时间:2023-10-16

比较两个时间规范值以查看哪个先发生的最佳方法是什么?

以下有什么问题吗?

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;
}

另一种方法是为timespec定义全局operator <()。 然后你可以比较一下,如果一个时间发生在另一个时间之前。

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