Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm working on a game loop in C++ using OpenGL and GLFW and it works like expected (I think), except when I'm focused in the window the FPS drops to 1fps (or 1000ms per frame) but when I'm not focused in the window the FPS is ~240fps. I think it has something to do with the timer, but I'm not quote sure why it would.

I'm running the program on OS X Yosemite 10.10.2 and building it with Xcode.

The debug output of the FPS:

333.333333 ms/frame (3 fps)
1000.000000 ms/frame (1 fps)
4.694836 ms/frame (213 fps)
4.149378 ms/frame (241 fps)
4.166667 ms/frame (240 fps)
4.166667 ms/frame (240 fps)
4.149378 ms/frame (241 fps)
4.149378 ms/frame (241 fps)
142.857143 ms/frame (7 fps)
1000.000000 ms/frame (1 fps)
4.716981 ms/frame (212 fps)

Here is the game loop code:

double unprocessedTime = 0;
double frameTime = (double)1 / (double)240;
double lastTime = glfwGetTime();
double frameCounter = 0;

int frames = 0;

bool isRunning = true;

while(isRunning)
{
    bool shouldRender = false;

    double startTime = glfwGetTime();
    double delta = startTime - lastTime;

    unprocessedTime += delta;
    frameCounter += delta;
    lastTime = startTime;

    while(unprocessedTime >= frameTime)
    {
        unprocessedTime -= frameTime;
        shouldRender = true;

        if(window.ShouldWindowClose())
        {
            isRunning = false;
        }

        game.Tick();

        if(frameCounter >= 1)
        {
            printf("%f ms/frame (%d fps)\n", ((double)1000 / frames), frames);

            frameCounter = 0;
            frames = 0;
        }
    }

    if(shouldRender)
    {
        game.Render();

        frames++;
    }
    else
    {
        usleep(1000);
    }
}
share|improve this question
    
What other profiling have you done? Which part of your loop is making the whole loop run so slowly? –  Byte56 Feb 17 at 15:30
    
It starts slowing down with the while(unprocessedTime >= frameTime) loop. When I comment out the while loop but leave its content intact, it runs at 60 fps when focussed, and 10k+ fps when unfocussed. –  Erik Verstegen Feb 17 at 19:05
    
Have you read up on the standard in this situation? gafferongames.com/game-physics/fix-your-timestep –  Byte56 Feb 17 at 19:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.