【问题标题】:Comparing timespec values比较 timespec 值
【发布时间】:2015-09-02 22:44:15
【问题描述】:

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

【问题讨论】:

  • 这看起来不错

标签: c++ linux gnu


【解决方案1】:

另一种方法是为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";

【讨论】:

  • 为了使它起作用,他必须决定这是一个 C 还是 C++ 问题。它目前被标记为两者。
  • @BrianMcFarland 是的。我是从 C++ 这边进来的,所以没看到 C 标签。
  • 视情况而定。
猜你喜欢
  • 2011-08-02
  • 2015-05-09
  • 1970-01-01
  • 2016-01-14
  • 2021-05-03
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多