【问题标题】:python memory leakpython内存泄漏
【发布时间】:2011-12-13 14:16:42
【问题描述】:

我有一个像这样创建的“单元”对象数组:

class Cell:
  def __init__(self, index, type, color):
    self.index = index
    self.type = type
    self.score = 0
    self.x = index%grid_size
    self.y = int(index/grid_size)
    self.color = colour


alpha = 0.8
b = 2.0
grid_size = 100
scale = 5

number_cells = grid_size*grid_size
num_cooperators = int(number_cells*alpha)       
cells = range(number_cells)
random.shuffle(cells)
cooperators = cells[0:num_cooperators]
defectors = cells[num_cooperators:number_cells]
cells = [Cell(i, 'C', blue) for i in cooperators]
cells += [Cell(i, 'D', red) for i in defectors]
cells.sort(compare)

我在这样的循环中从它们那里获取属性:

while 1:
    pixArr = pygame.PixelArray(windowSurfaceObj)
    for cell in cells:
        x = cell.x
        y = cell.y
        color = cell.color
        for y_offset in range(0,scale):
            for x_offset in range(0,scale):
                pixArr[x*scale + x_offset][y*scale + y_offset] = color
    del pixArr
    pygame.display.update()

我正在疯狂地泄漏内存......这是怎么回事?

【问题讨论】:

  • 你如何确定你正在泄漏内存?
  • 我注意到我的机器上播放的音乐开始跳动,所以我查看了我的系统活动。它从大约 100MB 的内存使用量开始,但很快就会达到 1 GB 或 2!
  • 那么number_cellsnum_cooperators呢?
  • 我猜你显示的循环是在另一个循环中世代相传。您是否为每一代存储pixArr
  • 请查看更新后的帖子,了解更多详情

标签: python memory-management memory-leaks pygame


【解决方案1】:

PixelArray 中似乎存在错误。

以下代码通过在每个循环中设置一个像素来复制内存泄漏,您甚至不必更新显示即可导致问题:

import pygame, sys
from pygame.locals import *
ScreenWidth, ScreenHeight = 640, 480
pygame.init()
Display = pygame.display.set_mode((ScreenWidth,ScreenHeight), 0, 32)
pygame.display.set_caption('Memory Leak Test')
while True:
    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()

如果您可以处理性能损失,用(非常短的)行替换直接像素设置可以避免内存泄漏,即:pygame.draw.line(Display, Colour, (X,Y), (X,Y), 1)

【讨论】:

  • 我在 Python 3.4.0 上并使用 PyGame 1.9.2a0,运行它不会给我泄漏。
【解决方案2】:

Cell 类可以通过使用槽来收紧(内存大小)。这应该会大大减少内存消耗:

class Cell(object):
    __slots__ = ('index', 'type', 'color')
    ...

您的代码中唯一的大型结构是 pixArr。您可能想使用 sys.getsizeof 监控它的大小。跟踪泄漏的另一个工具是漂亮地打印 gc.garbage

【讨论】:

    猜你喜欢
    • 2012-12-02
    • 2014-02-26
    • 2010-11-27
    • 2015-02-15
    • 1970-01-01
    • 2021-12-04
    • 2021-01-10
    • 2017-10-18
    • 2010-11-23
    相关资源
    最近更新 更多