mport time
def test():
for i in range ( 1000000 * 10 ):
del i
if ( __name__ == "__main__" ):
test()
while ( True ):
time.sleep( 1 )
观察mem:内存维持不变!
从这点可以猜测:python不是立即释放资源的.
个人测试代码:
-----------------------------------------------test0.py-------------------------------------
import time
def test():
for i in range ( 1000000 * 10 ):
del i
def test_2():
#i = range ( 1000000 * 10 )
#del i
pass
def test_3():
#i = "*" * ( 1000000 * 10 )
#del i
pass
if ( __name__ == "__main__" ):
for i in range( 10 ):
test()
test_2()
test_3()
time.sleep( 1 )
while ( True ):
time.sleep( 1 )
-----------------------------------------------------test0.py--------------------------------------
运行 python test0.py
"while ( True ):
time.sleep( 1 )
"
保证python不退出.
发现python的内存占用率为60%.
如何解决这个问题呢?看下面的:
-----------------------------------------------test1.py-------------------------------------
#coding=utf-8
import time
max_number = 1000000 * 10
def test_0():
for i in range ( max_number ):
del i
def test_1():
for i in range( 1000 ):
for i in range ( max_number / 1000 ):
del i
if ( __name__ == "__main__" ):
#test_0()#内存使用率占40%
test_1()#内存使用率占0.2%
print "---------------------"
while ( True ):
time.sleep( 1 )
-----------------------------------------------test1.py-------------------------------------
我想问题:问题也许解决了.
这就要看你的实际需求是什么了.
例如:
我做过一个爬虫程序,如果不断往这个线程里面传递url,那么这个线程不到一会就挂了.我的改进方法:就是控制这线程能够接受的url队列长度.以及其他的优化.
其实这个不是循环导致的内存被python持有,而是range( n )让python分配了很多的内存.退出test(),python回收内存,但是python并不释放了,而是让pool持有内存空间.