3

2 つの 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 に答える