Python Memory Leak
I have an array of 'cell' objects created like so: class Cell: def __init__(self, index, type, color): self.index = index self.type = type self.score = 0 self.x =
Solution 1:
There appears to be a bug in PixelArray.
The following code replicates the memory leak by setting a single pixel each loop, and you don't even have to update the display to cause the problem:
import pygame, sys
from pygame.localsimport *
ScreenWidth, ScreenHeight = 640, 480
pygame.init()
Display = pygame.display.set_mode((ScreenWidth,ScreenHeight), 0, 32)
pygame.display.set_caption('Memory Leak Test')
whileTrue:
PixelArray = pygame.PixelArray(Display)
PixelArray[ScreenWidth-1][ScreenHeight-1] = (255,255,255)
del PixelArray
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#pygame.display.update()
If you can handle the performance hit, replacing direct pixel setting with (very short) lines avoids the memory leak, ie: pygame.draw.line(Display, Colour, (X,Y), (X,Y), 1)
Solution 2:
The Cell class can be tighted-up (memorysize) by using slots. That ought to substantially reduce memory consumption:
classCell(object):
__slots__ = ('index', 'type', 'color')
...
The only large structure in your code is pixArr. You might want to monitor its size with sys.getsizeof. Another tool for tracking down leaks is to pretty print gc.garbage.
Post a Comment for "Python Memory Leak"