1

2 つのタイムスタンプの時差を取得しようとしています。スレッドは 2 つのタイム スタンプの間でスリープ状態です。しかし、違いを得ると、スレッドがスリープしていた時間がわかりません。私のコードは以下です。

#include <iostream>
#include <locale>
#include <sys/time.h>
#include <cstdlib>
#include <unistd.h>

using namespace std;

int timeInMilli();

int main()
{
  timeval t;
  timeval t2;
  gettimeofday(&t, NULL);
  gettimeofday(&t2, NULL);

  std::string buf(20, '\0');
  std::strftime(&buf[0], buf.size(), "%H:%M:%S:", localtime(&t.tv_sec));

  std::string hr  = buf.substr(0, 2);
  std::string min = buf.substr(3, 2);
  std::string sec = buf.substr(6, 2);

/*std::cout << hr  << '\n';
  std::cout << min << '\n';
  std::cout << std::atoi(sec.c_str()) << '\n';*/

  int a = timeInMilli();
  usleep(10);
  int b = timeInMilli();

  cout << b-a << endl;    
}

int timeInMilli()
{
  timeval t;
  gettimeofday(&t, NULL);

  string buf(20, '\0');
  strftime(&buf[0], buf.size(), "%H:%M:%S:", localtime(&t.tv_sec));
  string str_hr  = buf.substr(0, 2);
  string str_min = buf.substr(3, 2);
  string str_sec = buf.substr(6, 2);

  int hr    = atoi(str_hr.c_str());
  int min   = atoi(str_min.c_str());
  int sec   = atoi(str_sec.c_str());
  int milli = t.tv_usec/1000;

/*cout << hr    << endl;
  cout << min   << endl;
  cout << sec   << endl;
  cout << milli << endl;*/

  int timeInMilli = (((hr * 60) + min) * 60 + sec) * 1000 + milli;
  return timeInMilli;
}
4

1 に答える 1

2
usleep(10);

usleep はマイクロ秒で動作するため、 10ミリ秒はなく 10マイクロ秒一時停止することを意味します。で試してください

usleep(10000);
于 2013-10-17T10:11:25.320 に答える