Any way to speed up Python and Pygame?

ApprenticeHacker picture ApprenticeHacker · Jun 18, 2011 · Viewed 24.3k times · Source

I am writing a simple top down rpg in Pygame, and I have found that it is quite slow.... Although I am not expecting python or pygame to match the FPS of games made with compiled languages like C/C++ or event Byte Compiled ones like Java, But still the current FPS of pygame is like 15. I tried rendering 16-color Bitmaps instead of PNGs or 24 Bitmaps, which slightly boosted the speed, then in desperation , I switched everything to black and white monochrome bitmaps and that made the FPS go to 35. But not more. Now according to most Game Development books I have read, for a user to be completely satisfied with game graphics, the FPS of a 2d game should at least be 40, so is there ANY way of boosting the speed of pygame?

Answer

Alexander picture Alexander · Jun 18, 2011

Use Psyco, for python2:

import psyco
psyco.full()

Also, enable doublebuffering. For example:

from pygame.locals import *
flags = FULLSCREEN | DOUBLEBUF
screen = pygame.display.set_mode(resolution, flags, bpp)

You could also turn off alpha if you don't need it:

screen.set_alpha(None)

Instead of flipping the entire screen every time, keep track of the changed areas and only update those. For example, something roughly like this (main loop):

events = pygame.events.get()
for event in events:
    # deal with events
pygame.event.pump()
my_sprites.do_stuff_every_loop()
rects = my_sprites.draw()
activerects = rects + oldrects
activerects = filter(bool, activerects)
pygame.display.update(activerects)
oldrects = rects[:]
for rect in rects:
    screen.blit(bgimg, rect, rect)

Most (all?) drawing functions return a rect.

You can also set only some allowed events, for more speedy event handling:

pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP])

Also, I would not bother with creating a buffer manually and would not use the HWACCEL flag, as I've experienced problems with it on some setups.

Using this, I've achieved reasonably good FPS and smoothness for a small 2d-platformer.