Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 41 ยท Packaging and Next Steps

Pygame Performance, Profiling and Debugging

Make Pygame games faster and fix bugs: convert surfaces, show FPS, profile with cProfile, use spatial grids for collisions, avoid per-frame allocation and debug with logging.

At some point your game will slow down: the frame rate drops when there are many enemies, or the window stutters when the player shoots. Guessing at the cause wastes hours. This lesson gives you a method: measure first, find the real bottleneck, fix that, and measure again. It also collects the most effective Pygame speed-ups and a practical debugging toolkit.

The measuring tools (time.perf_counter, cProfile) are plain Python and run here. Window-related code is read-only.

Step one: know your frame budget

At 60 frames per second each frame has about 16.7 milliseconds to handle events, update everything and draw. If that total is 25 ms the game runs at 40 fps. Show the frame rate so you can see the effect of changes:

Python
fps = clock.get_fps()
label = font.render(f"{fps:.0f} fps", True, (255, 255, 0))
screen.blit(label, (8, 8))

clock.get_fps() averages the last ten frames. Also print the frame time in ms, and watch it while you play. Remember that Clock.tick(60) caps the rate, so a game that reports 60 fps may have lots of spare time; for benchmarking, call tick(0) or a large limit to see how fast the loop could run.

Step two: find the bottleneck with a profiler

Python includes cProfile, which records how long each function takes. Run your game (or a test loop) under it:

Python
import cProfile, pstats

profiler = cProfile.Profile()
profiler.enable()
run_for_300_frames()
profiler.disable()
pstats.Stats(profiler).sort_stats("cumulative").print_stats(8)

From a terminal, python -m cProfile -s cumtime main.py does the same for the whole run. Look for the functions with the highest cumulative time: those are where fixes pay off. Do not optimize anything that is not on that list.

Python Profile a slow and a fast version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The profile reports total function calls and time; the squared-distance version avoids the square root and the extra bookkeeping. Absolute timings vary by computer, so compare the two lines rather than memorizing numbers.

The biggest Pygame speed-ups

1. Convert your images. pygame.image.load returns a surface in the file's pixel format. After the window exists, call convert() (no transparency) or convert_alpha() (per-pixel transparency) once so blitting does not convert every time. This single call can make drawing several times faster.

Python
background = pygame.image.load("bg.png").convert()
ship = pygame.image.load("ship.png").convert_alpha()

2. Never load, scale or render text inside the loop. image.load, transform.scale, font.render and SysFont are slow. Do them once, or cache the result and re-render text only when the string changes.

3. Draw less. Skip off-screen objects (see Tilemaps and Scrolling Camera). Pre-draw a static background once instead of thousands of shapes each frame. Prefer a few large blits over many tiny ones.

4. Update only the changed regions with pygame.display.update(rect_list) when only a small part of the screen changes (a menu). For most games a full flip() is fine.

5. Use sprite groups with LayeredDirty only when you have many mostly-static sprites; otherwise plain Group.draw is fine.

6. Avoid per-frame allocation. Creating thousands of Vector2s and Surfaces every frame produces garbage collection pauses. Reuse objects or pool them.

7. Cut collision work. Comparing every object to every other object is O(n squared). With 1,000 bullets and enemies that is a million checks per frame.

Faster collisions: a spatial grid

Divide the world into cells. Each object registers in the cell it occupies; to find collisions, compare an object only with the others in the same or neighboring cells.

Python Brute force versus a spatial grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The grid finds exactly the same collisions with a tiny fraction of the tests. The cell size should be at least as large as the biggest object. In simple games pygame.sprite.groupcollide and spritecollide are fine until you pass a few hundred objects.

Measuring with perf_counter

For quick experiments time a section yourself:

Python
import time

t0 = time.perf_counter()
update_enemies(dt)
t1 = time.perf_counter()
draw_world(screen)
t2 = time.perf_counter()
print(f"update {1000*(t1-t0):.2f} ms, draw {1000*(t2-t1):.2f} ms")

If drawing takes most of the budget, reduce blits or convert surfaces; if updating dominates, look at your algorithms.

Python Timing sections of a frame

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The numbers depend on the machine; the habit of splitting the frame into sections is what matters.

Debugging toolkit

  • Read the traceback bottom up. The last line names the error; the lines above show the call path. pygame.error: display Surface quit means you used the screen after pygame.quit().
  • Print state sparingly. Printing 60 times per second floods the console and slows the game. Print on events or once per second.
  • Use logging instead of print: logging.debug(...) can be turned on or off without editing code.
  • Debug overlay. Toggle with F3 to draw hit-boxes (pygame.draw.rect(screen, "red", rect, 1)), the FPS, the player's position and the number of entities.
  • Slow motion and frame stepping. Add a key that sets dt to a fraction, or that runs one update per key press, to watch a collision bug frame by frame.
  • Seed random numbers (random.seed(1)) to make a bug reproducible.
  • Breakpoints. In VS Code or PyCharm place a breakpoint in the loop; when the debugger stops, inspect variables. For a one-off, insert breakpoint().
  • Assertions (assert 0 <= index < len(items)) catch impossible states near their source.
  • Binary search the bug. Disable half the systems; if the bug persists it is in the other half.

Typical errors and their usual cause

Message or symptom Usual cause
pygame.error: video system not initialized Missing pygame.init() or used after quit()
FileNotFoundError for an image Path relative to the wrong folder; use Path(__file__).parent
TypeError: invalid rect assignment Assigning a float where a Rect expects an int, or a tuple of wrong length
Window "not responding" The loop does not call pygame.event.get()
Sprite jitters Rounding the position into the Rect each frame; keep a float position
Game faster on one PC Movement without delta time
Black screen Forgot display.flip(), or drew before fill

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the time budget per frame at 60 frames per second?

    1000 ms divided by 60 frames is roughly 16.7 ms for events, updates and drawing.
  2. 2. Which call should be made once after loading an image to speed up blitting?

    It converts the pixel format to match the display so each blit needs no conversion.
  3. 3. Why does a spatial grid speed up collision checks?

    Brute force is O(n squared); the grid limits tests to nearby objects.
  4. 4. What should you do before optimizing code?

    Profiling shows where the time really goes, so you optimize the part that matters.

Summary

  • Know the frame budget (16.7 ms at 60 fps) and display the frame rate.
  • Profile with cProfile and time.perf_counter before changing anything.
  • Convert surfaces once, never load/scale/render inside the loop, draw only what is visible and avoid per-frame allocation.
  • Use spatial grids to cut collision work from O(n squared) to near-linear.
  • Debug with tracebacks, logging, overlays, frame stepping and seeded randomness.

Next: Packaging and Sharing Your Game