如何减去两个gettimeofday实例



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

思路是:

  static struct timeval tv;
  gettimeofday(&tv, NULL);
  static struct timeval tv2;
  gettimeofday(&tv2, NULL);
  static struct timeval tv3=tv2-tv;

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

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

如何手动完成(因为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';

相关内容

  • 没有找到相关文章

最新更新