I'm writing a real-time interactive graphics application using SDL2 and OpenGL in Python (pysdl2, PyOpenGL). The application continuously produces frames, which may change in response to keyboard / mouse input or based on time.
My main event loop, copied from some obscure source on the web that I can't find again, looks (simplified) like this:
event = sdl2.SDL_Event()
running = True
while running:
# process events
while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
if event.type == sdl2.SDL_QUIT:
running = False
# render frame
<some OpenGL commands>
sdl2.SDL_GL_SwapWindow(window)
sdl2.SDL_Delay(10)
From what I understand, the delay of 10 ms is intended to give the CPU some breathing room, and indeed, when I remove it the CPU usage doubles.
What I don't understand is why it is necessary. The graphics display is double buffered and buffer swaps are synchronized with the vertical retrace (60 Hz = 16 ms). Naively one would expect that if <some OpenGL commands> take less than 16 ms, then SDL_GL_SwapWindow will introduce a delay anyway, so SDL_Delay is not necessary. And if they use more than that, then the program is struggling to keep up with the display framerate, and introducing a delay would hurt.
Now from what I've been told in response to another question, the buffer swap and therefore the retrace synchronization doesn't happen when the SDL_GL_SwapWindow is executed, but this only puts a "sync & swap" instruction into an OpenGL queue, and this instruction gets executed when everything before has finished. The same holds for <some OpenGL commands>. But this instruction queue is finite, and therefore at some point my program, instead of waiting for the retrace, will wait for there to be space in the instruction queue. The end effect should be the same: If one execution of my event loop needs on average less than 16 ms, then the program will on average delay long enough to make it 16 ms per loop execution. So again, why is the explicit delay necessary?
As a second question: Considering the delay might hurt the framerate, is there a better way to let the CPU rest?
You don't need use
sdl2.SDL_Delay(10)because SDL_Delay is timer for SDL2 framework if you use event-loop then it doesn't need with SDL_Delay.My code for Python 3.10 looks example with KeyPress and Close window by mouse click
Remember that event-loop should like other in C/C++,. Java, C# or other programming langauges.
Without event-loop means you should use
SDL_Delay()then game window will close automacally.I hope you understand - I found Python examples but they look like weird and wrong - they write like "Latin".
I would like to improve who understands better like other programming languages. PS: I will work hard my github with clear examples :)