pygame-vs-raylib.md (14286B)
1 # PyGame vs. Raylib 2 3 ## Date: 2026/09/20 4 5 I implemented [Prim's algorithm](https://cp-algorithms.com/graph/mst_prim.html) to create a MST of a graph in Python. I also created a visualization of it, shown below. 6 7  8 9 (This graph has 250 vertices and 1,000 edges. The source code used to generate this visualization can be found [here](https://git.laack.co/blog/file/python/pygame-vs-raylib/prim.py.html)) 10 11 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. 12 13 As it relates to the animation, the following two things should be apparent: 14 15 1. The first frame must draw every edge and vertex of the graph in a greyed-out color. 16 2. Each subsequent frame only has to draw one additional edge, the newly traversed edge, and one additional vertex, the vertex we are visiting. 17 18 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. 19 20 \* I did rewrite the animation in C++ using Raylib so I could make it [my X11 wallpaper](https://git.laack.co/abg/), but that's for another blog post. 21 22 ## Raylib 23 24 ### Implementation 25 26 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: 27 28 ```python 29 import pyray as pr 30 31 # ... (other imports, Vertex class definition, Edge class definition) 32 33 pr.init_window(screen_width, screen_height, "prim") 34 35 # ... (other initialization) 36 37 texture = pr.load_render_texture(screen_width,screen_height) 38 39 while !done: 40 if first: 41 start = time.monotonic_ns() 42 43 # After calling begin_texture_mode(texture) all writes will be 44 # sent to the texture without having to specify we're writing to the 45 # texture. This is also how begin_drawing() works, but for frames. 46 47 pr.begin_texture_mode(texture) 48 pr.clear_background(pr.BLACK) 49 50 for edge in edge_list: 51 edge.draw_edge(pr.DARKGRAY) 52 for vertex in graph: 53 vertex.draw_vertex(pr.DARKGRAY) 54 55 pr.end_texture_mode() 56 57 source_rec = pr.Rectangle(0, 0, screen_width, screen_height) 58 dest_rec = pr.Rectangle(0, 0, screen_width, screen_height) 59 60 pr.begin_drawing() 61 pr.draw_texture_pro(texture.texture, source_rec, dest_rec, pr.Vector2(0, 0), 0, pr.WHITE) 62 pr.end_drawing() 63 64 first = False 65 66 end = time.monotonic_ns() 67 first_times.append(end - start) 68 69 continue 70 71 # ... (perform one step of Prim's algorithm) 72 73 if len(to_draw_edge) != 0 or len(to_draw_vert) != 0: 74 start = time.monotonic_ns() 75 76 pr.begin_texture_mode(texture) 77 78 for edge in to_draw_edge: 79 edge.draw_edge(pr.WHITE) 80 for vert in to_draw_vert: 81 vert.draw_vertex(pr.WHITE) 82 83 pr.end_texture_mode() 84 85 source_rec = pr.Rectangle(0, 0, screen_width, screen_height) 86 dest_rec = pr.Rectangle(0, 0, screen_width, screen_height) 87 88 pr.begin_drawing() 89 pr.draw_texture_pro(texture.texture, source_rec, dest_rec, pr.Vector2(0, 0), 0, pr.WHITE) 90 pr.end_drawing() 91 92 end = time.monotonic_ns() 93 redraw_times.append(end - start) 94 95 to_draw_vert = [] 96 to_draw_edge = [] 97 ``` 98 99 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. 100 101 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. 102 103 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: 104 105 ```python 106 pr.draw_circle(int(self.x),int(self.y), RADIUS, c) # vertex 107 pr.draw_line(int(self.v1.x), int(self.v1.y), int(self.v2.x), int(self.v2.y), c) # edge 108 ``` 109 110 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. 111 112 ## PyGame 113 114 ### Implementation 115 116 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: 117 118 ```python 119 120 # ... (imports and such) 121 122 pygame.init() 123 display = pygame.display.set_mode((screen_width,screen_height)) 124 125 # ... (other initialization) 126 127 while !done: 128 if first: 129 start = time.monotonic_ns() 130 131 display.fill(BLACK) 132 133 for edge in edge_list: 134 edge.draw_edge(display, LIGHT_GREY) 135 for vertex in graph: 136 vertex.draw_vertex(display, LIGHT_GREY) 137 138 pygame.display.update() 139 140 end = time.monotonic_ns() 141 first_time.append(end - start) 142 143 first = False 144 continue 145 146 # ... (perform one step of Prim's algorithm) 147 148 start = time.monotonic_ns() 149 150 for edge in to_draw_edge: 151 edge.draw_edge(display, white) 152 for vert in to_draw_vert: 153 vert.draw_vertex(display, white) 154 155 pygame.display.update() 156 end = time.monotonic_ns() 157 158 to_draw_vert = [] 159 to_draw_edge = [] 160 ``` 161 162 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: 163 164 ```python 165 pygame.draw.circle(display, WHITE, (self.x,self.y), RADIUS) 166 pygame.draw.line(display, WHITE, (self.v1.x,self.v1.y), (self.v2.x,self.v2.y), LINE_WIDTH) 167 ``` 168 169 (notice the first parameter is the surface to write to) 170 171 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. 172 173 ## Benchmarking 174 175 The benchmarks were executed under the following conditions: 176 177 - Vertex count: 2,500 178 - Edge count: 25,000 179 - Screen dimensions: 5120x1440 180 - CPU: 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz (4 cores, 8 threads) 181 - iGPU: Intel Corporation TigerLake-LP GT2 \[Iris Xe Graphics\] 182 - OS: Arch Linux 183 184 Additionally, the metrics are all **averages** across 10 full runs. 185 186 | Library | First frame time (ms) | Incremental frame time (ms) | 187 | - | -------------------------- | --------------- | 188 | Raylib | 29.87 ± 0.74 | 2.88 ± 1.11 | 189 | PyGame | 323.39 ± 44.60 | 5.59 ± 0.65 | 190 191 192 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. 193 194 ### Why Is PyGame So Slow? 195 196 Let's instrument our code to dig deeper: 197 198 ```python 199 if first: 200 start = time.monotonic_ns() 201 display.fill(BLACK) 202 203 edge_times = [] # new 204 vertex_times = [] # new 205 206 for edge in edge_list: 207 se = time.monotonic_ns() # new 208 edge.draw_edge(display, LIGHT_GREY) 209 ee = time.monotonic_ns() # new 210 edge_times.append(ee - se) # new 211 212 for vertex in graph: 213 sv = time.monotonic_ns() # new 214 vertex.draw_vertex(display, LIGHT_GREY) 215 ev = time.monotonic_ns() # new 216 vertex_times.append(ev - sv) # new 217 218 pygame.display.update() 219 end = time.monotonic_ns() 220 first_time.append(end - start) 221 222 first = False 223 224 print("Edge time avg: " + str(sum(edge_times) / len(edge_times))) # new 225 print("Vertex time avg: " + str(sum(vertex_times) / len(vertex_times))) # new 226 227 continue 228 ``` 229 230 (Notice the addition of timing for individual edge and vertex draw times for the first frame) 231 232 Let's also update our Raylib code to do the same: 233 234 ```python 235 if first: 236 start = time.monotonic_ns() 237 pr.begin_texture_mode(texture) 238 pr.clear_background(pr.BLACK) 239 240 edge_times = [] # new 241 vertex_times = [] # new 242 243 for edge in edge_list: 244 es = time.monotonic_ns() # new 245 edge.draw_edge(pr.DARKGRAY) 246 ee = time.monotonic_ns() # new 247 edge_times.append(ee - es) # new 248 for vertex in graph: 249 vs = time.monotonic_ns() # new 250 vertex.draw_vertex(pr.DARKGRAY) 251 ve = time.monotonic_ns() # new 252 vertex_times.append(ve - vs) # new 253 254 pr.end_texture_mode() 255 256 source_rec = pr.Rectangle(0, 0, screen_width, screen_height) 257 dest_rec = pr.Rectangle(0, 0, screen_width, screen_height) 258 259 pr.begin_drawing() 260 pr.draw_texture_pro(texture.texture, source_rec, dest_rec, pr.Vector2(0, 0), 0, pr.WHITE) 261 pr.end_drawing() 262 263 end = time.monotonic_ns() 264 first_time.append(end - start) 265 266 first = False 267 268 print("Edge time avg: " + str(sum(edge_times) / len(edge_times))) # new 269 print("Vertex time avg: " + str(sum(vertex_times) / len(vertex_times))) # new 270 271 continue 272 ``` 273 274 Running this updated code once we find: 275 276 | Library | Avg. Edge Draw Time (ns)| Avg. Vertex Draw Time (ns)| 277 | - | - | - | 278 | PyGame | 9504.15048 | 686.6508 | 279 | Raylib | 944.15884 | 3016.1852 | 280 281 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. 282 283 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. 284 285 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. 286 287 \* There are ways to change the rendering pipeline for PyGame to make better use of GPUs, but these approaches are either complex or experimental. 288 289 #### Is that why PyGame is slower? 290 291 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: 292 293 | Library | Expected First Frame Draw Time (ms)| Expected Subsequent Frame Draw Time (ms) | 294 | - | - | - | 295 | PyGame | 239.3204 | 0.0101908 | 296 | Raylib | 31.14443 | 0.003960344 | 297 298 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. 299 300 ##### PyGame Flamegraph 301 302 <img src="images/pygame-flamegraph.svg" style="max-width:100%; height:auto;"> 303 304 ##### Raylib Flamegraph 305 306 <img src="images/rlib-flamegraph.svg" style="max-width:100%; height:auto;"> 307 308 309 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: 310 311 | Library | Function | Average Call Time (ms)| 312 | - | - | - | 313 | PyGame | `EndDrawing()` | 5.677199 | 314 | Raylib | `pygame.display.update()`| 2.680623 | 315 316 Based on our original frame time benchmarks, these calls make up almost all of the time spent rendering subsequent frames. 317 318 #### What Are These Functions Doing? 319 320 In the case of Raylib, EndDrawing does a few things: 321 322 1. Calls `rlDrawRenderBatchActive()` 323 - This clears the batched geometries queue, issuing the OpenGL calls 324 2. Calls `SwapScreenBuffer()` 325 - This swaps the buffer the display scans out. In effect, this ensures the frame we just drew becomes visible. 326 - This is done by with `glfwSwapBuffers()`, but this is beyond scope as it requires an understanding of OpenGL and double buffering. 327 - 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. 328 3. Optionally waits to hit the target framerate in cases where rendering is happening faster than the target 329 330 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. 331 332 Let's step through the PyGame `update()` function too: 333 334 1. Calls `pg_update()` in `src_c/display.c` 335 - This performs some basic checks to make sure a display is set 336 2. `pg_update()` calls `SDL_UpdateWindowSurfaceRects` 337 - This copies the buffer into a buffer owned by the windowing system (X11 in my case) 338 339 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](https://en.wikipedia.org/wiki/Bit_blit). 340 341 ## Takeaways 342 343 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. 344 345 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.