原因:
1.Python 程序在运行时,需要在内存中开辟出一块空间,用于存放运行时产生的临时变量,计算完成后,再将结果输出到永久性存储器中。
2.但是当数据量过大,或者内存空间管理不善,就很容易出现内存溢出的情况,程序可能会被操作系统终止。
3.而对于服务器这种用于永不中断的系统来说,内存管理就显得更为重要了,不然很容易引发内存泄漏。
4.这里的内存泄漏是指程序本身没有设计好,导致程序未能释放已不再使用的内存,或者直接失去了对某段内存的控制,造成了内存的浪费。
1.函数外
# coding=utf-8
import os
import psutil
import gc, sys
# 显示当前 python 程序占用的内存大小
def show_memory_info(hint):
pid = os.getpid( )
p = psutil.Process(pid)
info = p.memory_full_info( )
memory = info.uss / 1024. / 1024
print('{} memory used: {} MB'.format(hint, memory))
def func( ):
global a # 1
show_memory_info('before')
a = [i for i in range(10000000)]
show_memory_info('after')
# return a # 2
func( ) # 1
# a = func( ) # 2
print("a引用次数:", sys.getrefcount(a))
del a # 计数为零
gc.collect( ) # 启动垃圾回收
show_memory_info('finished')
输出:
before memory used: 8.5234375 MB
after memory used: 396.484375 MB
a引用次数: 2
finished memory used: 9.3203125 MB
2.函数内–循环引用
# coding=utf-8
import os
import psutil
import gc, sys
# 显示当前 python 程序占用的内存大小
def show_memory_info(hint):
pid = os.getpid( )
p = psutil.Process(pid)
info = p.memory_full_info( )
memory = info.uss / 1024. / 1024
print('{} memory used: {} MB'.format(hint, memory))
def func( ):
show_memory_info('initial')
a = [i for i in range(10000000)]
b = [i for i in range(10000000)]
a.append(b)
b.append(a) # 引用了一次
print("a引用次数:", sys.getrefcount(a))
show_memory_info('after a, b created')
func( )
gc.collect( ) # 启动垃圾回收
show_memory_info('finished')
输出:
initial memory used: 8.59375 MB
a引用次数: 3
after a, b created memory used: 783.96484375 MB
finished memory used: 9.48828125 MB