【问题标题】:How to subtract two gettimeofday instances?如何减去两个 gettimeofday 实例?
【发布时间】:2012-01-29 22:05:52
【问题描述】:

我想减去两个 gettimeofday 实例,并以毫秒为单位给出答案。

想法是:

  static struct timeval tv;
  gettimeofday(&tv, NULL);

  static struct timeval tv2;
  gettimeofday(&tv2, NULL);

  static struct timeval tv3=tv2-tv;

然后将 'tv3' 转换为毫秒分辨率。

【问题讨论】:

  • 你自己搞不定? : 逐个字段相减,如果tv_usec为负数,则归一化结果!
  • 我认为有更好的方法,而不是使用 'if' 语句。

标签: c++ linux gettimeofday


【解决方案1】:

您可以使用 glibc 提供的 timersub() 函数,然后将结果转换为毫秒(不过,这样做时要注意溢出!)。

【讨论】:

  • 为什么会有溢出?
  • @user1106106:如果您减去的两个值恰好相隔超过“XXX_MAX”毫秒,那么显然转换为毫秒的结果将不适合“xxx”类型的单个变量..
【解决方案2】:

这里是手动操作的方法(因为 timersub 不是其他地方提供的标准功能)

struct timeval tv;
gettimeofday(&tv, NULL);
// ...
struct timeval tv2;
gettimeofday(&tv2, NULL);

int microseconds = (tv2.tv_sec - tv.tv_sec) * 1000000 + ((int)tv2.tv_usec - (int)tv.tv_usec);
int milliseconds = microseconds/1000;
struct timeval tv3;
tv3.tv_sec = microseconds/1000000;
tv3.tv_usec = microseconds%1000000;

(而且您必须注意溢出,这会使情况变得更糟)

不过,当前版本的 C++ 提供了更好的选择:

#include <chrono> // new time utilities

// new type alias syntax
using Clock = std::chrono::high_resolution_clock;
// the above is the same as "typedef std::chrono::high_resolution_clock Clock;"
//   but easier to read and the syntax supports being templated
using Time_point = Clock::time_point;

Time_point tp = Clock::now();
// ...
Time_point tp2 = Clock::now();

using std::chrono::milliseconds;
using std::chrono::duration_cast;
std::cout << duration_cast<milliseconds>(tp2 - tp).count() << '\n';

【讨论】:

  • 哎呀。你是对的。我把它和 tm 结构混在一起了。我会删除我的评论。
猜你喜欢
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
相关资源
最近更新 更多