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

Get time difference in milliseconds in c++

本文关键字:为单位 时差 c++ 获取      更新时间:2023-10-16

我正在尝试获取两个时间戳之间的时间差。线程在两个时间戳之间休眠。但是当我得到差异时,它不会给我线程休眠的时间。我的代码如下。

#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, '');
  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, '');
  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;
}
usleep(10);

意味着您暂停 10 微秒而不是 10 毫秒,因为 Usleep 以微秒为单位工作。 尝试使用

usleep(10000);