Skip to main content

Profiling — wiki

You can use this code to profile your pygame at the python level. With it you can find out the bits that are slowing down your game. If your game is going too slow, you will be able to find out what areas to improve.

If your main loop is not already in a main() function, just put it in one, and add the stuff below to your game.

def main():
    for x in range(10000):
        pass
        
import cProfile as profile
profile.run('main()')

Warning: the hotshot module has some bugs and may produce incorrect timings. Read the a python-dev mailing list thread titled "s/hotshot/lsprof" for details. It's better to use cProfile if you have python2.5+

import traceback,sys

def slow_function():
    # your code goes here.
    for x in range(10000):
        pass


def main():
    # your code goes here.
    slow_function()


if __name__ == "__main__":
    if "profile" in sys.argv:
        import hotshot
        import hotshot.stats
        import tempfile
        import os

        profile_data_fname = tempfile.mktemp("prf")
        try:
            prof = hotshot.Profile(profile_data_fname)
            prof.run('main()')
            del prof
            s = hotshot.stats.load(profile_data_fname)
            s.strip_dirs()
            print "cumulative\n\n"
            s.sort_stats('cumulative').print_stats()
            print "By time.\n\n"
            s.sort_stats('time').print_stats()
            del s
        finally:
            # clean up the temporary file name.
            try:
                os.remove(profile_data_fname)
            except:
                # may have trouble deleting ;)
                pass
    else:
        try:
            main()
        except:
            traceback.print_exc(sys.stderr)

Or if you're too lazy to copy all that in, this works as well (although not quite as fancily.)

Or you can use the @profile decorator from the profilehooks module by Marius Gedminas.

from profilehooks import profile

@profile
def main():
    ... # your code here

if __name__ == '__main__':
    main()