如何减去两个gettimeofday实例?

时间:2011-12-29 13:53:06

标签: c++ linux gettimeofday

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

这个想法是:

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

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

  static struct timeval tv3=tv2-tv;

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

2 个答案:

答案 0 :(得分:8)

你可以使用glibc提供的timersub()函数,然后将结果转换为毫秒(但是这样做时要小心溢出!)。

答案 1 :(得分:4)

以下是手动操作方法(因为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';