cj1*_*094 2 opengl performance
由于某种原因,以下代码生成如下结果:
我不知道为什么渲染每一帧需要一两秒钟.代码对我来说似乎是正常的,但我不知道为什么它如此缓慢地呈现它.
#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;
}
Run Code Online (Sandbox Code Playgroud)
您的GLFW代码是正确的,并且它的执行速度比您想象的要快得多.
这是不正确的使用rand
和srand
.更具体地说,您srand
每次渲染时都会显示当前时间(以秒为单位),这将在同一秒内r
每次生成完全相同的值.
因此,您每秒将屏幕清除几百次相同的颜色.这看起来只是每秒渲染一帧,但事实并非如此.
您的代码还有一些其他问题(例如使用rand()%100
它会产生偏差分布.并且冗余地使用一些OpenGL命令),但您需要解决的问题是: srand
只有一次,而不是每次渲染.