cj1094
cj1094

Reputation: 81

Why is my GLFW window so slow?

For some reason the following code produces a result such as this: enter image description here

I have no idea why it takes a second or two to render each frame. The code seems to be normal to me, but I have no idea why it renders it so slowly.

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

Upvotes: 2

Views: 2290

Answers (1)

Damon
Damon

Reputation: 70106

Your GLFW code is correct, and it is performing much faster than you think.

This is incorrect usage of rand and srand. More concretely, you srand with the current time (measured in seconds) every time you render, which will, within the same second, produce exactly the same value for r every time.

You therefore clear the screen to the same color several hundred times per second. This looks like it only renders at one frame per second, but it really isn't.

There are a few other problems with your code (such as using rand()%100 which gives a biased distribution. and using some OpenGL commands redundantly), but the one thing you need to fix for your immediate problem is: srand only once, not every time you render.

Upvotes: 5

Related Questions