将秒转换为std :: chrono :: duration吗?

问题描述:

我正在使用c ++ 11 < chrono> ,秒数表示为双精度。我想在这段时间内使用c ++ 11进行睡眠,但是我无法理解如何将其转换为 std :: chrono :: duration 对象c> std :: this_thread :: sleep_for 必需。

I'm using c++11 <chrono> and have a number of seconds represented as a double. I want to use c++11 to sleep for this duration, but I cannot fathom how to convert it to a std::chrono::duration object that std::this_thread::sleep_for requires.

const double timeToSleep = GetTimeToSleep();
std::this_thread::sleep_for(std::chrono::seconds(timeToSleep));  // cannot convert from double to seconds

我已经锁定了&lt ; chrono> 引用,但我觉得很混乱。

I've locked at the <chrono> reference but I find it rather confusing.

谢谢

编辑:

以下给出错误:

std::chrono::duration<double> duration(timeToSleep );
std::this_thread::sleep_for(duration);

错误:

c:\program files (x86)\microsoft visual studio 11.0\vc\include\chrono(749): error C2679: binary '+=' : no operator found which takes a right-hand operand of type 'const std::chrono::duration<double,std::ratio<0x01,0x01>>' (or there is no acceptable conversion)
2>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\chrono(166): could be 'std::chrono::duration<__int64,std::nano> &std::chrono::duration<__int64,std::nano>::operator +=(const std::chrono::duration<__int64,std::nano> &)'
2>          while trying to match the argument list '(std::chrono::nanoseconds, const std::chrono::duration<double,std::ratio<0x01,0x01>>)'
2>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\thread(164) : see reference to function template instantiation 'xtime std::_To_xtime<double,std::ratio<0x01,0x01>>(const std::chrono::duration<double,std::ratio<0x01,0x01>> &)' being compiled
2>          c:\users\johan\desktop\svn\jonsengine\jonsengine\src\window\glfw\glfwwindow.cpp(73) : see reference to function template instantiation 'void std::this_thread::sleep_for<double,std::ratio<0x01,0x01>>(const std::chrono::duration<double,std::ratio<0x01,0x01>> &)' being compiled


不要做 std :: chrono: :seconds(timeToSleep)。您想要更多类似的东西:

Don't do std::chrono::seconds(timeToSleep). You want something more like:

std::chrono::duration<double>(timeToSleep)

或者,如果 timeToSleep 的度量单位不是秒,则可以通过一个比率作为持续时间的模板参数。有关更多信息,请参见此处(及其中的示例)。

Alternatively, if timeToSleep is not measured in seconds, you can pass a ratio as a template parameter to duration. See here (and the examples there) for more information.