C++ std::this_thread::sleep_for() sleeping longer than expected for small durations

107 Views Asked by At

I'm encountering an issue with std::this_thread::sleep_for() in my C++ application. I'm using it to pause the main thread for a small duration to adjust my frame_rate, but I've noticed that when [sleep_duration] has a vlaue of say "0.01364" (13,64ms), it ends up sleeping for a longer period, approximately 8-10 milliseconds longer than expected. (I'm working on Windows 10, VS 2022)

here is my code for reference:

void application::run() {

    PFF_PROFILE_BEGIN_SESSION("runtime", "benchmarks", "PFF_benchmark_runtime.json");
    f32 max_frame_time = static_cast<f32>(1.0 / m_target_fps);

    while (m_running) {

        PFF_PROFILE_SCOPE("run");

        // update game...
        // render frame...

        m_work_time = static_cast<f32>(glfwGetTime()) - m_work_start_time;
        if (m_work_time < max_frame_time) {

            PFF_PROFILE_SCOPE("sleep");
            std::chrono::milliseconds sleep_duration(static_cast<int>((max_frame_time - m_work_time) * 1000));
            std::this_thread::sleep_for(sleep_duration);
            m_sleep_time = static_cast<f32>(sleep_duration.count());

        } else
            m_sleep_time = 0;

        CORE_LOG(Info, "sleep time: " << m_sleep_time);
        m_work_start_time = static_cast<f32>(glfwGetTime());
        m_fps = static_cast<u32>(1 / (m_work_time + m_sleep_time));
    }
    PFF_PROFILE_END_SESSION();

}

I've tried using a profiler to investigate, and it seems that the actual sleep duration is consistently longer than the requested duration.

What could be causing this discrepancy? Is there a more accurate way to achieve precise sleep durations in C++?

0

There are 0 best solutions below