gpt4 book ai didi

performance - 为什么我的 GLFW 窗口这么慢?

转载 作者:行者123 更新时间:2023-12-04 03:04:56 25 4
gpt4 key购买 nike

出于某种原因,以下代码会产生如下结果:enter image description here

我不知道为什么渲染每一帧需要一两秒。代码对我来说似乎很正常,但我不知道为什么它渲染得这么慢。

#define GLFW_INCLUDE_GLU
#define GLEW_STATIC
#include"GL/glew.c"
#include"GLFW/glfw3.h"
#include<cmath>
#include<ctime>
#include<stdlib.h>
using namespace std;

int main( ) {
// init glfw
if ( !glfwInit( ) ) return 0;

// create window and set active context
GLFWwindow* window = glfwCreateWindow( 640, 480, "Test", NULL, NULL );
glfwMakeContextCurrent( window );

// init glew
if ( glewInit( ) != GLEW_OK ) return 0;

// set swap interval
glfwSwapInterval( 1 );

// render loop
while ( !glfwWindowShouldClose( window ) ) {
srand( time( NULL ) );
float r = ( rand( ) % 100 ) / 100.0;

float ratio;
int width, height;
glfwGetFramebufferSize( window, &width, &height );
ratio = width / ( float ) height;
glViewport( 0, 0, width, height );

// render
glClear( GL_COLOR_BUFFER_BIT );
glClearColor( r, 0, 0, 1 );

// swap
glfwSwapBuffers( window );

// events
glfwPollEvents( );
}

// terminate glfw
glfwTerminate( );

return 0;
}

最佳答案

您的 GLFW 代码是正确的,并且它的执行速度比您想象的要快得多。

这是 randsrand 的错误用法。更具体地说,您每次渲染时都会使用当前时间(以秒为单位)进行srand,这将在同一秒内为r每次生成完全相同的值.

因此,您每秒将屏幕清除为相同颜色数百次。 看起来它仅以每秒一帧的速度渲染,但事实并非如此。

您的代码还存在一些其他问题(例如使用 rand()%100 会产生有偏差的分布。以及冗余地使用一些 OpenGL 命令),但您需要修复的一件事对于您眼前的问题是: srand 仅一次,而不是每次渲染时。

关于performance - 为什么我的 GLFW 窗口这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24955424/

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