比较TimePec值 [英] Comparing timespec values

查看:3
本文介绍了比较TimePec值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

以下内容有什么问题吗?

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

这篇关于比较TimePec值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆