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

std::chrono - fixed time step loop

本文关键字:循环 定时间 chrono std      更新时间:2023-10-16

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

这是我的代码:

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