下面的例子显示了一个典型的内存泄露:
#!/usr/local/bin/python2.7
class LeakTest(object):
def __init__(self):
print 'Object with id %d born here.' % id(self)
def __del__(self):
print 'Object with id %d dead here.' % id(self)
def foo():
A=LeakTest()
B=LeakTest()
A.b=B
B.a=A
foo()
[root@SJSWT44-122 ~]# python2.7 test.py
Object with id 47432678233872 born here.
Object with id 47432678233936 born here.
类似于死锁,导致互相的引用计数器都无法清零,因此无法释放掉内存 另外当对象成为容器对象的一个元素,引用计数器加1
objgraph is a module that lets you visually explore Python object graphs. 官方地址 下载之后,python setup.py install就安装成功了 主要是使用objgraph.show_most_common_types(limit=100)来显示当前内存中的对象
#注意leak_test对象必须继承object,否则objgraph无法侦察到
import objgraph
class leak_test(object):
def __init__(self):
property="abcd"
def __del__(self):
pass
array=[]
def test(array):
for i in range(1,100):
a=leak_test()
array.append(a)
print 'start'
test(array)
objgraph.show_most_common_types(limit=100)
print 'end'
参考文献: 1,Python中的内存泄漏 2,python内存泄露的诊断 3,python垃圾回收机制对list.append()的性能影响