花费时间以毫秒为单位

Ram*_*uri 4 c++

我在unistd.h中找到了usleep函数,我认为在每个动作之前等待一段时间是有用的.但是我发现线程只是在它没有接收到任何信号时才会睡觉.例如,如果我按下一个按钮(我正在使用OpenGL,但问题是更具体的关于time.h和unistd.h),线程被唤醒,我没有得到我想要的.在time.h中,有一个sleep函数接受一个整数,但是一个整数太多了(我想等0.3秒),所以我使用了usleep.我问是否有一个函数需要花费时间(以毫秒为单位)(来自任何GNU或任何库).它应该像time()一样工作,但是返回毫秒而不是秒.这可能吗?

man*_*ler 9

如果你有提升,你可以这样做:

#include <boost/thread.hpp>

int main()
{
  boost::this_thread::sleep(boost::posix_time::millisec(2000));
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这个简单的例子,你可以在代码中看到,睡眠时间为2000毫秒.

编辑:

好吧,我以为我理解了这个问题,但后来我读了评论,现在我不再那么肯定了.

也许你想知道自某个点/事件以来经过了多少毫秒?如果是这种情况,那么你可以这样做:

#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <iostream>


int main()
{
  boost::chrono::high_resolution_clock::time_point start = boost::chrono::high_resolution_clock::now();
  boost::this_thread::sleep(boost::posix_time::millisec(2000));
  boost::chrono::milliseconds ms = boost::chrono::duration_cast<boost::chrono::milliseconds> (boost::chrono::high_resolution_clock::now() - start);
  std::cout << "2000ms sleep took " << ms.count() << "ms " << "\n";
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

(请原谅长线)