std::chrono - fixed time step loop

2019-07-30 16:02发布

问题:

I'm trying to make fixed time step loop with using < chrono >.

This is my code:

#include <iostream>
#include <chrono>

int main()
{
    std::chrono::steady_clock::time_point start;
    const double timePerFrame = 1.0 / 60.0;
    double accumulator = 0.0;
    int i = 0;
    while(true)
    {
        start = std::chrono::steady_clock::now();
        while(accumulator >= timePerFrame)
        {
            accumulator -= timePerFrame;
            std::cout << ++i << std::endl;
            //update();
        }
        accumulator += std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - start).count();
        //render();
    }
    return 0;
}

Value of variable "i" is printed less then 60 times a second. The same situation takes place when I'm trying to change "timePerFrame" to "1.0". What is wrong with it?

回答1:

#include <iostream>
#include <chrono>
#include <thread>

int main()
{
    using namespace std::chrono;
    using Framerate = duration<steady_clock::rep, std::ratio<1, 60>>;
    auto next = steady_clock::now() + Framerate{1};
    int i = 0;
    while(true)
    {
        std::cout << ++i << std::endl;
        //update();
        std::this_thread::sleep_until(next);
        next += Framerate{1};
        //render();
    }
    return 0;
}

Here's the same thing with a busy loop:

int main()
{
    using namespace std::chrono;
    using Framerate = duration<steady_clock::rep, std::ratio<1, 60>>;
    auto next = steady_clock::now() + Framerate{1};
    int i = 0;
    while(true)
    {
        std::cout << ++i << std::endl;
        //update();
        while (steady_clock::now() < next)
            ;
        next += Framerate{1};
        //render();
    }
    return 0;
}