gpt4 book ai didi

c++ - GLFW 3.0/C++ 中的空闲线程时间

转载 作者:太空狗 更新时间:2023-10-29 21:23:58 38 4
gpt4 key购买 nike

我试图强制 GLFW 3.0 停止对我的 CPU 进行核攻击,然后再将其作为框架推进以促进 API 的学习。我以 http://www.glfw.org/documentation.html 为例并开始四处寻找限制它的方法。

目前,我的工作是:

#include <iostream>
#include <chrono>
#include <thread>
#include <GLFW/glfw3.h>

int main(void)
{
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds milliseconds;

Clock::time_point currentTime, newTime;
milliseconds frameTime;

GLFWwindow* window;

if (!glfwInit())
return -1;

window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}

glfwMakeContextCurrent(window);

while (!glfwWindowShouldClose(window))
{
currentTime = Clock::now();

glfwSwapBuffers(window);

glfwPollEvents();

newTime = Clock::now();

frameTime = std::chrono::duration_cast<milliseconds>(newTime - currentTime);

if(frameTime.count() < 16)
std::this_thread::sleep_for(milliseconds(16 - frameTime.count()));

std::cout << "Frame time: " << frameTime.count() << "ms" << std::endl;
}

glfwTerminate();
return 0;

由于 GLFW 已经将自己限制为 60fps,我认为这可能有效。而且,事实上,它在主循环运行时将我的 CPU 使用率减半。现在这可能已经足够好了,但我真正想知道的是:

如何让 GLFW 等待信号并释放 CPU 而不是只是在 while 循环中烤轮胎?我无法想象它完全没有这个功能。

最佳答案

一般来说,你不需要。通常,您的程序实际上会在那段时间做一些事情。如果您没有事情要做,那么您就可以腾出一些时间来处理其他流程。如果没有其他进程可运行,您只需吞下它,直到您准备好运行。

渲染器通常会尝试尽可能快地渲染,因为它们通常无法超过 GPU。这就是大多数游戏的运作方式;他们尝试尽快执行。如果 CPU 比他们预期的快得多,他们可能会有计时器来做一些屈服,但通常情况下,他们只是让渲染器运行。

此外,期待 sleep_for实际返回 milliseconds(16 - frameTime.count()) 时间是不合理的。这只是最低估计,不是要求。

最好用yield为此。

关于c++ - GLFW 3.0/C++ 中的空闲线程时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17138579/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com