2013-07-27 9 views
15

私はC++ 11 <chrono>を使用しています。秒数は2倍になります。私はこの期間中、C++ 11をスリープ状態にしたいですが、std::this_thread::sleep_forに必要なオブジェクトstd::chrono::durationに変換する方法はわかりません。秒をstd :: chrono :: durationに倍精度に変換しますか?

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

私は<chrono>参照でロックしましたが、私はそれがむしろ混乱を見つけます。

おかげ

EDIT:

次のようにエラーを与える:

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

エラー:

:\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 
+1

コーンスターチの答えは正しいです。これはVS11 'std :: this_thread :: sleep_for'のバグのようです。このバグを回避するには、 'std :: this_thread :: sleep_for(std :: chrono:duration_cast (duration))'を試すことができます。私は任意にミリ秒を選んだ。どんなものを使ってもかまいませんが、 ''はあなたのものを転がすのではなく、コンバージョンを提供します。 –

答えて

16

std::chrono::seconds(timeToSleep)をしないでください。 timeToSleepを秒単位で測定されていない場合

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

あるいは、あなたがdurationにテンプレートパラメータとして比率を渡すことができます:あなたはより多くのような何かをしたいです。詳細については、here(およびその例)を参照してください。

4
const unsigned long timeToSleep = static_cast<unsigned long>(GetTimeToSleep() * 1000); 
std::this_thread::sleep_for(std::chrono::milliseconds(timeToSleep)); 
0
std::chrono::milliseconds duration(timeToSleep); 
std::this_thread::sleep_for(duration);