Search code examples
c++sdlframe-rate

C++ SDL framerate drops when holding key down


I'm trying to make a simple tile-based platformer in C++ and SDL2. My framerate stays at 59-60 fps, but when I start to hold down a key, it loses about 10 fps. This happens even when I don't call update or retrieve the keystates. This is the code inside my game loop:

//keys = (Uint8 *)SDL_GetKeyboardState(NULL);
elapsed = SDL_GetTicks() - current;
current += elapsed;
timeSinceSecond += elapsed;
//update(keys, elapsed / 1000.0);
draw();
frames++;

if(timeSinceSecond >= 1000) {
    timeSinceSecond = 0;
    cout << frames << endl;
    frames = 0;
}

next = SDL_GetTicks();
if(next - current < 1000.0 / framerate) {
    SDL_Delay(1000.0 / framerate - (next - current));
}

Any ideas on why this is happening? Could it be that it's a problem with SDL2? I haven't tried this with SDL 1.2.


Solution

  • SDL_Delay will not work the way you want. It is not precise enough (has 10 millisecond precision), so it will be impossible to get required number of frames per second this way. Us vsync instead. Another thing is that printing to stderr/stdout is slow when console is visible. If you're printing something when key is pressed, or if pressing the key somehow increases amount of text being printed, game will slow down.