2017-12-24 1 views
0

つまり、私はstd::this_thread::sleep_for(std::chrono::milliseconds(10));をプログラムループで使用しています。私が10ミリ秒間眠ったら。 1秒を得るために何を増やす必要がありますか?

このループで増分され、経過秒数が表示される変数がある場合は、何を増やす必要がありますか?各ステップの

すなわちfloat x = 0;

x += 0.01 

私は0.1、0.01、0.001を試してみたが、それらはすべて、速すぎたり遅すぎるのいずれかに見えます。

+1

'のstd :: this_thread :: sleep_for(STD ::クロノ::ミリ秒(10));'正確ではないかもしれません。おそらく、このアプローチ(この例では1つ)を代わりに使用するべきです:http://en.cppreference.com/w/cpp/thread/sleep_for – drescherjm

+0

絶対的な時点を使用して 'sleep_until'を使うことをお勧めします。そうすることで、ドリフトを避けることができます。 – Galik

+3

あなたはスリープ期間の** real duration **を取得する必要があります:スリープ状態に入る前に(例えば 'chrono :: high_resolution_clock :: now()'を呼ぶことによって)開始時間を保存し、スリープ後の終了時間を保存し、それらの値を減算します。その後、この期間をミリ秒や秒にキャストすることができます。 – VTT

答えて

4

絶対の時点とwait_until()を使用することをおすすめします。このようなもの:

// steady_clock is more reliable than high_resolution_clock 
auto const start_time = std::chrono::steady_clock::now(); 
auto const wait_time = std::chrono::milliseconds{10}; 
auto next_time = start_time + wait_time; // regularly updated time point 

for(;;) 
{ 
    // wait for next absolute time point 
    std::this_thread::sleep_until(next_time); 
    next_time += wait_time; // increment absolute time 

    // Use milliseconds to get to seconds to avoid 
    // rounding to the nearest second 
    auto const total_time = std::chrono::steady_clock::now() - start_time; 
    auto const total_millisecs = double(std::chrono::duration_cast<std::chrono::milliseconds>(total_time).count()); 
    auto const total_seconds = total_millisecs/1000.0; 

    std::cout << "seconds: " << total_seconds << '\n'; 
} 
関連する問題