1

I'm trying to get the time difference between two time stamps. Thread is sleeping between the two time stamps. but when i get the difference, it doesn't give me the time which the thread was sleeping. My code is below.

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

意味着您暂停 10微秒而不是 10毫秒,因为 usleep 使用微秒。尝试

usleep(10000);
于 2013-10-17T10:11:25.320 回答