How to limit FPS in a loop with C++?

后端 未结 4 1415
不思量自难忘°
不思量自难忘° 2021-01-30 22:38

I\'m trying to limit the frames per second in a loop that is performing intersection checking, using C++ with chrono and thread.

Here is my code:

std::ch         


        
4条回答
  •  猫巷女王i
    2021-01-30 23:23

    If you think about how your code works, you'll find out that it works exactly how you wrote it. Delta oscillates because of a logical mistake in the code.

    This is what happens:

    • We start with delta == 0.
    • Because the delta is smaller than 200, you code sleeps 200 - delta(0) == 200 ms.
    • Now, the delta itself becomes close to 200 (because you've measured that sleep time as well as an actual work) and you sleep 200 - delta(200) == 0 ms.
    • After that the cycle repeats.

    To fix the problem you need to not measure the sleep time.

    This is how it can be done:

    #include 
    #include 
    #include 
    #include 
    
    std::chrono::system_clock::time_point a = std::chrono::system_clock::now();
    std::chrono::system_clock::time_point b = std::chrono::system_clock::now();
    
    int main()
    {
        while (true)
        {
            // Maintain designated frequency of 5 Hz (200 ms per frame)
            a = std::chrono::system_clock::now();
            std::chrono::duration work_time = a - b;
    
            if (work_time.count() < 200.0)
            {
                std::chrono::duration delta_ms(200.0 - work_time.count());
                auto delta_ms_duration = std::chrono::duration_cast(delta_ms);
                std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count()));
            }
    
            b = std::chrono::system_clock::now();
            std::chrono::duration sleep_time = b - a;
    
            // Your code here
    
            printf("Time: %f \n", (work_time + sleep_time).count());
        }
    }
    

    This code gives me a steady sequence of deltas:

    Time: 199.057206 
    Time: 199.053581 
    Time: 199.064718 
    Time: 199.053515 
    Time: 199.053307 
    Time: 199.053415 
    Time: 199.053164 
    Time: 199.053511 
    Time: 199.053280 
    Time: 199.053283    
    

提交回复
热议问题