Your program is being a CPU hog! In some cases, this situation can actually make your program run slowly! Your code needs to give some time back to the OS (i.e. delay or sleep). Use SDL_Delay(Uint32), where the Uint32 is in milliseconds. As a quick fix, you can toss a SDL_Delay(1) call into your loop. That will give up some amount of time, based on the OS and the resolution of SDL_Delay(), which is somewhere around 10ms. If you need better resolution than that, you have to store the time it takes to perform SDL_Delay(1), check that against delay calls, and then burn the rest of the time in an empty loop. Here's a link to some code implementing that.

Now for an example. This code collects info about how long each frame takes. It uses this to comply with a framerate that you choose.

#define FPS 40
Uint32 waittime = 1000.0f/FPS;
Uint32 framestarttime = 0;
Sint32 delaytime;
bool done = 0;

    // Do stuff


    delaytime = waittime - (SDL_GetTicks() - framestarttime);
    if(delaytime > 0)
    framestarttime = SDL_GetTicks();
Carefully consider your framerates so that slower computers can run your program. You might even decide to let the user control the framerate. I do this with GigaSun Jet by separating the logic and the drawing framerates. The logic runs at a constant rate no matter the system, while the drawing framerate is adjustable through an options menu. This way, slower computers can give up smooth animation for speed. Another little thing I did was to implement frameskip. If the user has a drawing framerate that is too high and would cause the logic to be delayed, the drawing is skipped whenever the logic needs to run.

If your program still runs slowly, consider optimizations to your code. First of all, make sure that you use SDL_DisplayFormat() or SDL_DisplayFormatAlpha() to convert your images for fast blitting. Don't forget to free the originals if you don't need them. If your scene is not scrolling, look up some info on dirty rects (updating only the parts of the screen that you use). If your world is big, look into quadtrees (space partitioning) or scene graphs. You can also use SDL_GetTicks() and check how long each part of your loop takes to run. Try to optimize the bottlenecks. In general, though, the drawing is what slows you down. If you can avoid unnecessary drawing, you'll see some nice results.

This post was originally found here: