Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 获取以毫秒为单位的时间差,单位为c++;_C++_Thread Sleep - Fatal编程技术网

C++ 获取以毫秒为单位的时间差,单位为c++;

C++ 获取以毫秒为单位的时间差,单位为c++;,c++,thread-sleep,C++,Thread Sleep,我想知道两个时间戳之间的时差。线程在两个时间戳之间休眠。但是当我得到差异时,它并没有给我线程睡眠的时间。我的代码如下 #include <iostream> #include <locale> #include <sys/time.h> #include <cstdlib> #include <unistd.h> using namespace std; int timeInMilli(); int main() { time

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

#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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int timeInMilli();
int main()
{
timeval t;
时间间隔t2;
gettimeofday(&t,NULL);
gettimeofday(&t2,NULL);
std::字符串buf(20',\0');
std::strftime(&buf[0],buf.size(),%H:%M:%S:,localtime(&t.tv_秒));
std::string hr=buf.substr(0,2);
std::string min=buf.substr(3,2);
std::string sec=buf.substr(6,2);
/*标准::cout
这意味着您暂停10微秒,而不是10毫秒,因为usleep的工作时间为微秒。请尝试

usleep(10000);

它给了你什么?它给了我一些错误的答案。比如3,1,0是的,这是正确的,你能告诉我为什么它给了我一些近似值,比如11,12,13,10吗?你的计算机也做其他与你的程序并行的任务,所以执行时间会有一点不同。@Sameera如Atle所说,这是一个原子问题,你的计算机不会现在只做这个任务。如果答案对你有帮助,你可以接受:)好的,伙计们,谢谢你分享你的知识。这对我真的很有帮助。
usleep(10000);