2017-12-24 16 views
0

즉, 저는 프로그램 루프에서 std::this_thread::sleep_for(std::chrono::milliseconds(10));을 사용하고 있습니다.10 밀리 초 동안 잠을 자면. 잠깐 기다리려면 무엇을해야합니까?

초당 경과 시간을 표시하도록이 루프에서 증가하는 변수가있는 경우 무엇을 증가시켜야합니까? 각 단계에 대한 즉 float x = 0;

은 :

x += 0.01 

나는 0.1, 0.01, 0.001,하지만 그들은 모두가 너무 빠르거나 너무 느리게 중 하나 보인다 시도했습니다.

+1

'표준 : this_thread :: sleep_for (표준 : 크로노 :: 밀리 초 (10));'정확하지 않을 수 있습니다. 아마도이 접근법 (예제에서 하나)을 대신 사용해야 할 것입니다. http://en.cppreference.com/w/cpp/thread/sleep_for – drescherjm

+0

절대 sleep_until을 사용하고 절대 시간대를 사용하는 것이 좋습니다. 그렇게하면 표류를 피할 수 있습니다. – Galik

+3

경과 된 수면 기간의 ** 실제 시간 **을 확보해야합니다. 예를 들어'chrono :: high_resolution_clock :: now() '를 호출하여) 잠자기 전에 시작 시간을 저장 한 다음 잠자기 후 종료 시간을 저장하고 마지막으로 그 값을 뺍니다. 그런 다음이 지속 시간을 밀리 초 또는 초 또는 기타로 캐스팅 할 수 있습니다. – VTT

답변

4

절대 시간대 및 wait_until()을 사용하는 것이 좋습니다. 이런 식으로 뭔가 : 1 초

// 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'; 
}