python内存泄漏 [英] python memory leak

查看:132
本文介绍了python内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 = 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)

我正在像这样循环获取它们的属性:

I am grabbing attributes from them in a loop like so:

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()

我正在疯狂地泄漏记忆……发生了什么事?

I am leaking memory like crazy... what's going on?

推荐答案

PixelArray中似乎存在错误.

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.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)

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)

这篇关于python内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆