在c ++中获取以毫秒为单位的时间差

时间:2013-10-17 10:01:20

标签: c++ thread-sleep

我正试图获得两个时间戳之间的时差。线程在两个时间戳之间休眠。但是当我得到差异时,它并没有给我线程正在睡觉的时间。我的代码如下。

#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;
}

1 个答案:

答案 0 :(得分:2)

usleep(10);

表示暂停10 μsec而不是10 msec ,因为usleep的工作时间为微​​秒。试试

usleep(10000);