【问题标题】:How to limit FPS in a loop with C++?如何使用 C++ 限制循环中的 FPS?
【发布时间】:2016-12-08 09:20:00
【问题描述】:

我正在尝试使用带有计时和线程的 C++ 来限制执行交叉检查的循环中的每秒帧数。

这是我的代码:

std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::chrono::system_clock::time_point lastFrame = std::chrono::system_clock::now();

while (true)
{
    // Maintain designated frequency of 5 Hz (200 ms per frame)
    now = std::chrono::system_clock::now();
    std::chrono::duration<double, std::milli> delta = now - lastFrame;
    lastFrame = now;

    if (delta.count() < 200.0)
    {
        std::chrono::duration<double, std::milli> delta_ms(200.0 - delta.count());
        auto delta_ms_duration = std::chrono::duration_cast<std::chrono::milliseconds>(delta_ms);
        std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count()));
    }

    printf("Time: %f \n", delta.count());

    // Perform intersection test

}

我遇到的问题是 delta 的所有其他输出都显示微不足道的数量,而不是我的目标约为 200 毫秒/帧:

Time: 199.253200
Time: 2.067700
Time: 199.420400
Time: 2.408100
Time: 199.494200
Time: 2.306200
Time: 199.586800
Time: 2.253400
Time: 199.864000
Time: 2.156500
Time: 199.293800
Time: 2.075500
Time: 201.787500
Time: 4.426600
Time: 197.304100
Time: 4.530500
Time: 198.457200
Time: 3.482000
Time: 198.365300
Time: 3.415400
Time: 198.467400
Time: 3.595000
Time: 199.730100
Time: 3.373400

对为什么会发生这种情况有任何想法吗?

【问题讨论】:

  • 您的时间似乎约为 200 毫秒,那么问题出在哪里?你不能指望得到任何接近准确时间的东西。你得到的比 200 少一点,然后你得到的多一点,处理它 - 你不会每次都得到正好 200。
  • 我的目标不是精确的时间,但我不明白为什么有些循环迭代是 1-4 毫秒,而另一些是 ~200 毫秒。
  • 因为有时你的 deltacount
  • 操作系统可以随时安排您的程序 - 原因之一。你可能在某个地方做了一些愚蠢的事情,比如睡了一段时间......
  • 假设由于所有睡眠的精度比预期的要短,您首先睡眠 198 毫秒,因此 delta 约为 198 毫秒,因此睡眠约 2 毫秒,因此您的 delta 约为 2 毫秒。

标签: c++ chrono


【解决方案1】:

如果您考虑一下您的代码是如何工作的,您会发现它完全按照您编写的方式工作。 Delta 因代码中的逻辑错误而振荡。

会发生这样的事情:

  • 我们从delta == 0开始。
  • 因为 delta 小于 200,所以您的代码会休眠 200 - delta(0) == 200 毫秒。
  • 现在,delta 本身变得接近 200(因为您已经测量了睡眠时间以及实际工作)并且您睡眠 200 - delta(200) == 0 毫秒。
  • 之后循环重复。

要解决此问题,您无需测量睡眠时间。

可以这样做:

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

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<double, std::milli> work_time = a - b;

        if (work_time.count() < 200.0)
        {
            std::chrono::duration<double, std::milli> delta_ms(200.0 - work_time.count());
            auto delta_ms_duration = std::chrono::duration_cast<std::chrono::milliseconds>(delta_ms);
            std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_duration.count()));
        }

        b = std::chrono::system_clock::now();
        std::chrono::duration<double, std::milli> sleep_time = b - a;

        // Your code here

        printf("Time: %f \n", (work_time + sleep_time).count());
    }
}

这段代码给了我一个稳定的增量序列:

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    

【讨论】:

  • 很好的解释,我现在知道我哪里出错了。谢谢。
  • 不需要 sleep_fo()r 内的对话,证明:static_assert(std::is_same()," ");不会失败,
  • 但是这段代码每次循环调用两次系统时钟,效率很低。
【解决方案2】:

这很像Galik's answer,但它保留了 OP 问题的语法,并且不会下降到 C API。此外,它为帧持续时间创建了一个自定义单位,我认为这对可读性很重要:

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

int
main()
{
    using namespace std;
    using namespace std::chrono;

    using frames = duration<int64_t, ratio<1, 5>>;  // 5Hz
    auto nextFrame = system_clock::now();
    auto lastFrame = nextFrame - frames{1};;

    while (true)
    {
        // Perform intersection test

        this_thread::sleep_until(nextFrame);
        cout << "Time: "  // just for monitoring purposes
             << duration_cast<milliseconds>(system_clock::now() - lastFrame).count()
             << "ms\n";
        lastFrame = nextFrame;
        nextFrame += frames{1};
    }
}

这为我输出:

Time: 200ms
Time: 205ms
Time: 205ms
Time: 203ms
Time: 205ms
Time: 205ms
Time: 200ms
Time: 200ms
Time: 200ms
...

注意事项:

  • 记录 5Hz 的简明方式:using frames = duration&lt;int64_t, ratio&lt;1, 5&gt;&gt;;
  • 使用sleep_until 而不是sleep_for,它可以处理完成实际工作需要多长时间的未知数。
  • 除了 I/O 和 here's a library to get rid of that,不使用 .count()
  • 无需手动转换单位(例如/ 1000)。
  • 没有浮点单元,并不是说有什么问题。
  • 极少需要指定或依赖明确的单位。

加上duration I/O library,上面的代码将如何改变:

#include "chrono_io.h"
#include <chrono>
#include <cstdint>
#include <iostream>
#include <thread>

int
main()
{
    using namespace date;
    using namespace std;
    using namespace std::chrono;

    using frames = duration<int64_t, ratio<1, 5>>;  // 5Hz
    auto nextFrame = system_clock::now();
    auto lastFrame = nextFrame - frames{1};;

    while (true)
    {
        // Perform intersection test

        this_thread::sleep_until(nextFrame);
        // just for monitoring purposes
        cout << "Time: " << system_clock::now() - lastFrame << '\n';
        lastFrame = nextFrame;
        nextFrame += frames{1};
    }
}

输出会因平台而异(取决于system_clock 的“本机持续时间”)。在我的平台上是这样的:

Time: 200042µs
Time: 205105µs
Time: 205107µs
Time: 200044µs
Time: 205105µs
Time: 200120µs
Time: 204307µs
Time: 205136µs
Time: 201978µs
...

【讨论】:

  • 当我将比率更改为 30 或 60 Hz - error C2679: binary '+=': no operator found which takes a right-hand operand of type 'frames' (or there is no acceptable conversion) - 知道为什么吗?
  • 是的,这是编译器警告您在将 1/30 秒(例如)添加到 system_clock::time_point 时出现截断错误,因为 system_clock::time_point 不能完全表示 1/ 30 秒。但这很容易解决!只需将frames{0} 添加到 system_clock::now() 并让auto 发挥它的魔力:auto nextFrame = system_clock::now() + frames{0};。现在,您不再使用 system_clock::time_point 进行交易,而是使用可以准确表示帧总和和 system_clock::time_point 精度的 time_point。
【解决方案3】:

我通常会这样做:

#include <chrono>
#include <iostream>

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

输出:(每秒五个值)

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

【讨论】:

  • 这是我最喜欢的,除了我会定义一个自定义的frame 单位:using frames = std::chrono::duration&lt;std::int64_t, std::ratio&lt;1, 5&gt;&gt;;,然后做next_from += frames{1};。这样可以避免手动转换代码。
【解决方案4】:

交替的增量时间是由逻辑问题引起的:您根据前一帧的持续时间(根据帧持续时间的计算方式)为一帧添加延迟。这意味着在长帧(约 200 毫秒)之后,您不会应用延迟并获得短帧(几毫秒),然后会在下一帧触发延迟,从而产生长帧,依此类推。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    相关资源
    最近更新 更多