How to subtract two gettimeofday instances?

2019-05-18 04:09发布

I want to subtract two gettimeofday instances, and present the answer in milliseconds.

The idea is:

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

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

  static struct timeval tv3=tv2-tv;

and then convert 'tv3' into milliseconds resolution.

2条回答
地球回转人心会变
2楼-- · 2019-05-18 04:50

You can use the timersub() function provided by glibc, then convert the result to milliseconds (watch out for overflows when doing this, though!).

查看更多
做个烂人
3楼-- · 2019-05-18 04:58

Here's how to do it manually (since timersub isn't a standard function offered elsewhere)

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;

(and you have to watch for overflow, which makes it even worse)

The current version of C++ offers a better option though:

#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';
查看更多
登录 后发表回答