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

后端 未结 4 1445
不思量自难忘°
不思量自难忘° 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条回答
  •  自闭症患者
    2021-01-30 23:28

    I usualy do something like this:

    #include 
    #include 
    
    int main()
    {
        using clock = std::chrono::steady_clock;
    
        auto next_frame = clock::now();
    
        while(true)
        {
            next_frame += std::chrono::milliseconds(1000 / 5); // 5Hz
    
            // do stuff
            std::cout << std::time(0) << '\n'; // 5 for each second
    
            // wait for end of frame
            std::this_thread::sleep_until(next_frame);
        }
    }
    

    Output: (five for each second value)

    1470173964
    1470173964
    1470173964
    1470173964
    1470173964
    1470173965
    1470173965
    1470173965
    1470173965
    1470173965
    1470173966
    1470173966
    1470173966
    1470173966
    1470173966
    

提交回复
热议问题