I’m writing a game in SDL that needs to constantly check for keyboard input from the player. Using PollEvent(&e)
in my game loop works fine, but it eats up all available CPU cycles. When I put in the loop SDL_Delay(10)
it seems to work fine, but I couldn’t find anything about this on the web. I was wondering how often other developers poll for input.
Peter
You’ll find that when you place game logic and screen updates in the game loop, PollEvent is not holding the CPU up, so you still need to call it every until it returns 0 every frame. The loop itself is keeping the CPU busy.
If you use SDL_RENDERER_PRESENTVSYNC when creating the renderer, then it should wait until the monitor has refreshed (usually 60 times a second), which will free up the CPU. Or, you can use SDL_GetTicks() with a SDL_Delay(1) to decide how often to update game logic, draw the screen, etc. Personally I like to let the game loop thrash the CPU and allow the user to choose if vsync is enabled, so they can see how many fps their expensive PC goes beyond the monitor refresh rate, so long as your game logic is based on ticks, rather than game loop iterations.
Thanks for the quick reply. If I understand correctly, you’re suggesting polling input once a frame?
If by frame, you mean once every time the game loops, then that’s standard practice. So if you have a 60hz monitor and vsync is enabled, this would be 60 times a second. without vsync, this could be 1000+ times a second. SDL_PollEvent won’t slow your loop down.
1 Like
Sort of. Your polling loop should run once whenever you update your game state.
SDL_Event e;
while (1) { /* running */
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
goto quit;
}
/* check other events here */
}
update_game();
render_game();
/* delay somewhere if vsync is off */
}
quit:
/* cleanup and exit */
It is also possible to update the game and render it independently, but it’s more involved than this simple game loop.
2 Likes