Rather recently I learned about a handy little program called Valgrind. I get to use it to debug some C++ code that works with dynamic memory to fix any leaks that occurred. As it turns out, this program can do a lot more.
Something I’ve noticed for a while now is that Graff takes up a pretty significant amount of memory–around 40 megabytes of RAM. I never really thought about it too hard until now, but I discovered that with the command:
valgrind --tool=massif python Start.py ... ms_print massif.out.** > output
it takes snapshots of Graff’s memory usage. The first time running this and opening up “output” gives this result:
So currently I get ~43MB usage of the heap (or in python terms, plain memory) by just opening up the program and running around. Later in that output file, I notice a lot of calls to “SDL_CreateRGBSurface (in /usr/lib/libSDL-1.2.so.0.11.2)” seem to be eating up the most memory percentage-wise.
Doing some digging, I find out pygame converts images into a .RAW format for fast blitting–unfortunately, the file size is pretty hefty. Looking through my code, I notice that within Entity.py, when an entity is initialized, it loads up a file called “tiles.png” to pull the entity’s picture out of that and use it. After that, that loaded image is just kept there, permanently until the program quits. Tiles.png is only 42.3KB, though, which seems a little weird.
I decide to see just how many times entity loads up this image and stores it away forever. It turns out that this file is being loaded around 200 times, and is then saved as a member variable “self.sheet”. Since we don’t need it anymore once the entity’s image is ripped out of that sprite sheet, I decide to add one extra line to my code:
, after the entity’s image is set. What does that memory chart look like now?
15.64 MB is now used. By adding one extra line of code to delete an unused part of the code, I cut memory usage by 2/3!
Tinkering around some more, I find the pygame init routines take up a total of about 5MB, which means the code portion that I wrote takes up about 10MB of RAM. Perhaps now I’ll start paying attention to where memory ends up in Graff.