blog

Personal blog
git clone git://git.laack.co/blog.git
Log | Files | Refs

pygame-vs-raylib.gmi (14735B)


      1 # PyGame vs. Raylib
      2 
      3 ## Date: 2026/09/20
      4 
      5 I implemented Prim's algorithm to create a MST of a graph in Python. I also created a visualization of it, shown below.
      6 
      7 => https://cp-algorithms.com/graph/mst_prim.html
      8 => https://blog.laack.co/videos/prim.mkv
      9 
     10 This graph has 250 vertices and 1,000 edges. The source code used to generate this visualization can be found here:
     11 
     12 => https://git.laack.co/blog/file/python/pygame-vs-raylib/prim.py.html
     13 
     14 Prim's algorithm is worth understanding (albeit out of scope), and the problem it solves is finding the set of edges that minimizes the sum of their weights while guaranteeing there is exactly one path between any two vertices in the connected, weighted, undirected graph. In the case of my implementation, the weight of each edge was its length. 
     15 
     16 As it relates to the animation, the following two things should be apparent:
     17 
     18 * The first frame must draw every edge and vertex of the graph in a greyed-out color.
     19 * Each subsequent frame only has to draw one additional edge, the newly traversed edge, and one additional vertex, the vertex we are visiting.
     20 
     21 While we could render each frame from scratch based on the graph's state, any reasonable rendering program has the ability to additively draw geometries to avoid this re-computation, and I care a bit about performance (even though this is written in Python*). Since PyGame and Raylib both support this, I'll be using additive rendering in both of my implementations.
     22 
     23 (I did rewrite the animation in C++ using Raylib so I could make it my X11 wallpaper, but that's for another blog post)
     24 
     25 => https://git.laack.co/abg/
     26 
     27 ## Raylib
     28 
     29 ### Implementation
     30 
     31 Raylib has 2D rendered textures that can persist across frames. Here's some Python code that makes use of them to visualize Prim's algorithm:
     32 
     33 ```python
     34 import pyray as pr
     35 
     36 # ... (other imports, Vertex class definition, Edge class definition)
     37 
     38 pr.init_window(screen_width, screen_height, "prim")
     39 
     40 # ... (other initialization)
     41 
     42 texture = pr.load_render_texture(screen_width,screen_height)
     43 
     44 while !done:
     45     if first:
     46         start = time.monotonic_ns()
     47 
     48         # After calling begin_texture_mode(texture) all writes will be 
     49         # sent to the texture without having to specify we're writing to the 
     50         # texture. This is also how begin_drawing() works, but for frames.
     51 
     52         pr.begin_texture_mode(texture)
     53         pr.clear_background(pr.BLACK)
     54 
     55         for edge in edge_list:
     56             edge.draw_edge(pr.DARKGRAY)
     57         for vertex in graph:
     58             vertex.draw_vertex(pr.DARKGRAY)
     59 
     60         pr.end_texture_mode()
     61 
     62         source_rec = pr.Rectangle(0, 0, screen_width, screen_height)
     63         dest_rec = pr.Rectangle(0, 0, screen_width, screen_height)
     64 
     65         pr.begin_drawing()
     66         pr.draw_texture_pro(texture.texture, source_rec, dest_rec, pr.Vector2(0, 0), 0, pr.WHITE)
     67         pr.end_drawing()
     68 
     69         first = False
     70 
     71         end = time.monotonic_ns()
     72         first_times.append(end - start)
     73 
     74         continue
     75 
     76     # ... (perform one step of Prim's algorithm)
     77 
     78     if len(to_draw_edge) != 0 or len(to_draw_vert) != 0:
     79         start = time.monotonic_ns()
     80 
     81         pr.begin_texture_mode(texture)
     82 
     83         for edge in to_draw_edge:
     84             edge.draw_edge(pr.WHITE)
     85         for vert in to_draw_vert:
     86             vert.draw_vertex(pr.WHITE)
     87 
     88         pr.end_texture_mode()
     89 
     90         source_rec = pr.Rectangle(0, 0, screen_width, screen_height)
     91         dest_rec = pr.Rectangle(0, 0, screen_width, screen_height)
     92 
     93         pr.begin_drawing()
     94         pr.draw_texture_pro(texture.texture, source_rec, dest_rec, pr.Vector2(0, 0), 0, pr.WHITE)
     95         pr.end_drawing()
     96 
     97         end = time.monotonic_ns()
     98         redraw_times.append(end - start)
     99 
    100         to_draw_vert = []
    101         to_draw_edge = []
    102 ```
    103 
    104 Before our main iteration loop we initialize our texture. Then on our first iteration of the loop we draw each of the edges and vertices in our graph. On each subsequent iteration we only draw vertices added to `to_draw_vert` and edges added to `to_draw_edge`. Both lists are populated with edges and vertices that were visited since the last frame was rendered. 
    105 
    106 This code is also instrumented to track the amount of time the first frame takes to render, and the amount of time each subsequent frame takes to render as well.
    107 
    108 Not included above are our Vertex and Edge classes which both implement draw functions. These functions have the following lines to draw geometries with Raylib:
    109 
    110 ```python
    111 pr.draw_circle(int(self.x),int(self.y), RADIUS, c) # vertex
    112 pr.draw_line(int(self.v1.x), int(self.v1.y), int(self.v2.x), int(self.v2.y), c) # edge
    113 ```
    114 
    115 Per the code comment in the larger code snippet, Raylib uses global state to track which canvas is being drawn to, so these functions can be called in texture mode or drawing mode with a similar effect.
    116 
    117 ## PyGame
    118 
    119 ### Implementation
    120 
    121 PyGame persists frame state across frames by default so we don't have to mess with rendered textures like we did with Raylib! Here's a some code that does the PyGame rendering:
    122 
    123 ```python
    124 
    125 # ... (imports and such)
    126 
    127 pygame.init()
    128 display = pygame.display.set_mode((screen_width,screen_height))
    129 
    130 # ... (other initialization)
    131 
    132 while !done:
    133     if first:
    134         start = time.monotonic_ns()
    135 
    136         display.fill(BLACK)
    137 
    138         for edge in edge_list:
    139             edge.draw_edge(display, LIGHT_GREY)
    140         for vertex in graph:
    141             vertex.draw_vertex(display, LIGHT_GREY)
    142 
    143         pygame.display.update()
    144 
    145         end = time.monotonic_ns()
    146         first_time.append(end - start)
    147 
    148         first = False
    149         continue
    150 
    151     # ... (perform one step of Prim's algorithm)
    152 
    153     start = time.monotonic_ns()
    154 
    155     for edge in to_draw_edge:
    156         edge.draw_edge(display, white)
    157     for vert in to_draw_vert:
    158         vert.draw_vertex(display, white)
    159 
    160     pygame.display.update()
    161     end = time.monotonic_ns()
    162 
    163     to_draw_vert = []
    164     to_draw_edge = []
    165 ```
    166 
    167 I find this code to be more readable than the Raylib code because we don't have to maintain a standalone texture, and I also like how writing to a display is more explicit in PyGame:
    168 
    169 ```python
    170 pygame.draw.circle(display, WHITE, (self.x,self.y), RADIUS)
    171 pygame.draw.line(display, WHITE, (self.v1.x,self.v1.y), (self.v2.x,self.v2.y), LINE_WIDTH)
    172 ```
    173 
    174 (notice the first parameter is the surface to write to)
    175 
    176 Despite this, the final `pygame.display.update()` is still using global state, which feels a bit strange given we have to specify which surface we are drawing to.
    177 
    178 ## Benchmarking
    179 
    180 The benchmarks were executed under the following conditions:
    181 
    182 * Vertex count: 2,500
    183 * Edge count: 25,000
    184 * Screen dimensions: 5120x1440
    185 * CPU: 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz (4 cores, 8 threads)
    186 * iGPU: Intel Corporation TigerLake-LP GT2 \[Iris Xe Graphics\]
    187 * OS: Arch Linux
    188 
    189 Additionally, the metrics are all **averages** across 10 full runs.
    190 
    191 ```
    192 | Library | First frame time (ms)       | Incremental frame time (ms)  |
    193 | ------- | --------------------------- | ---------------------------- |
    194 | Raylib  | 29.87 +- 0.74               | 2.88 +- 1.11                 |
    195 | PyGame  | 323.39 +- 44.60             | 5.59 +- 0.65                 |
    196 ```
    197 
    198 
    199 In this benchmark Raylib's average incremental frame render time was ~2x faster than PyGame's, and its first frame render time was ~11x faster.
    200 
    201 ### Why Is PyGame So Slow?
    202 
    203 Let's instrument our code to dig deeper:
    204 
    205 ```python
    206 if first:
    207     start = time.monotonic_ns()
    208     display.fill(BLACK)
    209 
    210     edge_times = [] # new
    211     vertex_times = [] # new
    212 
    213     for edge in edge_list:
    214         se = time.monotonic_ns() # new
    215         edge.draw_edge(display, LIGHT_GREY)
    216         ee = time.monotonic_ns() # new
    217         edge_times.append(ee - se) # new
    218 
    219     for vertex in graph:
    220         sv = time.monotonic_ns() # new
    221         vertex.draw_vertex(display, LIGHT_GREY)
    222         ev = time.monotonic_ns() # new
    223         vertex_times.append(ev - sv) # new
    224 
    225     pygame.display.update()
    226     end = time.monotonic_ns()
    227     first_time.append(end - start)
    228 
    229     first = False
    230 
    231     print("Edge time avg: " + str(sum(edge_times) / len(edge_times))) # new 
    232     print("Vertex time avg: " + str(sum(vertex_times) / len(vertex_times))) # new
    233 
    234     continue
    235 ```
    236 
    237 (Notice the addition of timing for individual edge and vertex draw times for the first frame)
    238 
    239 Let's also update our Raylib code to do the same:
    240 
    241 ```python
    242 if first:
    243     start = time.monotonic_ns()
    244     pr.begin_texture_mode(texture)
    245     pr.clear_background(pr.BLACK)
    246 
    247     edge_times = [] # new
    248     vertex_times = [] # new
    249 
    250     for edge in edge_list:
    251         es = time.monotonic_ns() # new
    252         edge.draw_edge(pr.DARKGRAY)
    253         ee = time.monotonic_ns() # new
    254         edge_times.append(ee - es) # new
    255     for vertex in graph:
    256         vs = time.monotonic_ns() # new
    257         vertex.draw_vertex(pr.DARKGRAY)
    258         ve = time.monotonic_ns() # new
    259         vertex_times.append(ve - vs) # new
    260 
    261     pr.end_texture_mode()
    262 
    263     source_rec = pr.Rectangle(0, 0, screen_width, screen_height)
    264     dest_rec = pr.Rectangle(0, 0, screen_width, screen_height)
    265 
    266     pr.begin_drawing()
    267     pr.draw_texture_pro(texture.texture, source_rec, dest_rec, pr.Vector2(0, 0), 0, pr.WHITE)
    268     pr.end_drawing()
    269 
    270     end = time.monotonic_ns()
    271     first_time.append(end - start)
    272 
    273     first = False
    274 
    275     print("Edge time avg: " + str(sum(edge_times) / len(edge_times))) # new
    276     print("Vertex time avg: " + str(sum(vertex_times) / len(vertex_times))) # new
    277 
    278     continue
    279 ```
    280 
    281 Running this updated code once we find:
    282 
    283 ```
    284 | Library | Avg. Edge Draw Time (ns) | Avg. Vertex Draw Time (ns)|
    285 | ------- | ------------------------ | ------------------------- |
    286 | PyGame  | 9504.15048               | 686.6508                  |
    287 | Raylib  | 944.15884                | 3016.1852                 |
    288 ```
    289 
    290 PyGame is faster at drawing vertices (circles), but slower at drawing edges (lines). Since we are drawing many more edges than we are vertices, this contributes to making PyGame slower. 
    291 
    292 PyGame is slower at drawing lines because it uses SDL which computes lines pixel by pixel on the CPU\*, while Raylib appends the line ends to a queue for batch processing, to be asynchronously processed by the GPU.
    293 
    294 In the case of vertices, Raylib calls `DrawCircleSector()`, and this in turn appends geometries to the GPU drawing queue, but each circle is made of many discrete geometries which are each appended to the queue, costing cycles. Contrasting this with the PyGame approach where PyGame only has to draw a few pixels onto the surface.
    295 
    296 (There are ways to change the rendering pipeline for PyGame to make better use of GPUs, but these approaches are either complex or experimental)
    297 
    298 ### Is that why PyGame is slower?
    299 
    300 That's not the fully story. Let's consider what the numbers above mean. The first frame renders 2,500 vertices, 25,000 edges. Each subsequent frame renders 1 vertex and 1 edge. If we multiply these numbers with the values we calculated for the amount of time each draw takes, we get the following expected frame times:
    301 
    302 ```
    303 | Library | Expected First Frame Draw Time (ms)| Expected Subsequent Frame Draw Time (ms) |
    304 | ------- | ---------------------------------- | ---------------------------------------- |
    305 | PyGame  | 239.3204                           | 0.0101908                                |
    306 | Raylib  | 31.14443                           | 0.003960344                              |
    307 ```
    308 
    309 Based on this, we see the first frame times are on par with what we actually saw in our benchmarking, but the subsequent frame draw times are orders of magnitude faster than what we benchmarked, and since most frames are subsequent frames, they are severely impacting performance. Let's see if we can figure out why this disparity exists.
    310 
    311 ### PyGame Flamegraph
    312 
    313 => https://blog.laack.co/images/pygame-flamegraph.svg
    314 
    315 ### Raylib Flamegraph
    316 
    317 => https://blog.laack.co/images/rlib-flamegraph.svg
    318 
    319 We see most of our time is being spent in `EndDrawing()` for Raylib and `pygame.display.update()` for Pygame. After instrumenting these calls we find the following times per invocation:
    320 
    321 ```
    322 | Library | Function                  | Average Call Time (ms)|
    323 | ------- | ------------------------- | --------------------- |
    324 | PyGame  | `EndDrawing()`            | 5.677199              |
    325 | Raylib  | `pygame.display.update()` | 2.680623              |
    326 ```
    327 
    328 Based on our original frame time benchmarks, these calls make up almost all of the time spent rendering subsequent frames.
    329 
    330 ### What Are These Functions Doing?
    331 
    332 In the case of Raylib, EndDrawing does a few things:
    333 
    334 Calls `rlDrawRenderBatchActive()`
    335 * This clears the batched geometries queue, issuing the OpenGL calls
    336 Calls `SwapScreenBuffer()`
    337 * This swaps the buffer the display scans out. In effect, this ensures the frame we just drew becomes visible.
    338 * This is done by with `glfwSwapBuffers()`, but this is beyond scope as it requires an understanding of OpenGL and double buffering.
    339 * In the normal case (which is how our code uses it), this function returns after the instructions have been issued, not once the frame has been rendered.
    340 Optionally waits to hit the target framerate in cases where rendering is happening faster than the target
    341 
    342 Most of the time spent here is on the second step. This is because issuing the instructions to swap will flush the driver's command stream, and once a few frames are in flight, this will block until the GPU retires one.
    343 
    344 Let's step through the PyGame `update()` function too:
    345 
    346 Calls `pg_update()` in `src_c/display.c`
    347 * This performs some basic checks to make sure a display is set
    348 `pg_update()` calls `SDL_UpdateWindowSurfaceRects`
    349 * This copies the buffer into a buffer owned by the windowing system (X11 in my case)
    350 
    351 The main reason this is slower is PyGame copies the whole frame on the CPU for each frame while Raylib's frame is already in VRAM and the swap doesn't blit.
    352 
    353 => https://en.wikipedia.org/wiki/Bit_blit
    354 
    355 ## Takeaways
    356 
    357 Out of the box Raylib has better performance because it performs hardware accelerated rendering. In terms of ergonomics, they both have their own quirks. Raylib feels like a C library with Python bindings (because it is!), while PyGame feels inconsistent, mixing both explicit surface drawing, and global state for frame updates.
    358 
    359 Personally, I'm not keen on using PyGame again because I enjoy writing performant software, and the reality of Python is it can't be performant. This doesn't mean I won't ever write Python code again, it's useful for first passes at a problem, but if I want to productionize that software I'll have to rewrite it in a sensible programming language. The nice thing about doing a first pass on a project in Raylib is you can then rewrite it in C using Raylib directly, but the same isn't true for PyGame.