3

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

这个想法是:

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

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

  static struct timeval tv3=tv2-tv;

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

4

2 回答 2

8

您可以使用 glibc 提供的 timersub() 函数,然后将结果转换为毫秒(不过,在执行此操作时要注意溢出!)。

于 2011-12-29T14:01:40.550 回答
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';
于 2011-12-29T14:30:57.050 回答