std::chrono - 固定时间步循环

std::chrono - fixed time step loop

我正在尝试使用 进行固定时间步长循环。

这是我的代码:

#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;
}

变量 "i" 的值每秒打印少于 60 次。当我试图将 "timePerFrame" 更改为“1.0”时,也会发生同样的情况。有什么问题吗?

#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;
}

这是一个繁忙的循环:

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