我最近遇到本文 http://deeplearning.net/software/theano/tutorial/python-memory-management.html关于python内存分配。
在这个页面中,它描述了 python 的内存使用情况,并且有一个示例显示了整数列表的深度复制。我自己在 Python 2.7 上做了基准测试
Line # Mem usage Increment Line Contents
================================================
4 28.051 MiB 0.000 MiB @profile
5 def function():
6 59.098 MiB 31.047 MiB x = list(range(1000000)) # allocate a big list
7 107.273 MiB 48.176 MiB y = copy.deepcopy(x)
8 99.641 MiB -7.633 MiB del x
9 99.641 MiB 0.000 MiB return y
所以直接删除 x 只会删除 x 以及所有对 x 的整数的引用,对吧?
这样做也无济于事(那么 del x 和 del x[:] 有什么区别?):
Line # Mem usage Increment Line Contents
================================================
4 28.047 MiB 0.000 MiB @profile
5 def function():
6 59.094 MiB 31.047 MiB x = list(range(1000000)) # allocate a big list
7 107.270 MiB 48.176 MiB y = copy.deepcopy(x)
8 99.637 MiB -7.633 MiB del x[:]
9 99.637 MiB 0.000 MiB return y
与深层复制相反,如果我使用复制,删除后似乎内存会恢复到新创建 x 时的先前状态
Line # Mem usage Increment Line Contents
================================================
4 28.039 MiB 0.000 MiB @profile
5 def function():
6 59.090 MiB 31.051 MiB x = list(range(1000000)) # allocate a big list
7 66.895 MiB 7.805 MiB y = copy.copy(x)
8 59.262 MiB -7.633 MiB del x[:]
9 59.262 MiB 0.000 MiB return y
对于字典:
Line # Mem usage Increment Line Contents
================================================
4 28.051 MiB 0.000 MiB @profile
5 def function():
6 100.523 MiB 72.473 MiB x = dict((e, e) for e in xrange(1000000))
7 183.398 MiB 82.875 MiB y = copy.deepcopy(x)
8 135.395 MiB -48.004 MiB del x
9 135.395 MiB 0.000 MiB return y
对于列表列表(与整数列表相比,我假设 del x 或 del x[:] 只删除堆上的巨大数组列表?):
Line # Mem usage Increment Line Contents
================================================
4 28.043 MiB 0.000 MiB @profile
5 def function():
6 107.691 MiB 79.648 MiB x = [[] for _ in xrange(1000000)]
7 222.312 MiB 114.621 MiB y = copy.deepcopy(x)
8 214.680 MiB -7.633 MiB del x[:]
9 214.680 MiB 0.000 MiB return y
所以我想问:
- 那么如果没有办法收回那些被整数占用的内存呢?整数也是一个对象,对吗?为什么内存根本没有被释放?不能只要求整数吗?或者还有浮动和字符串?对象引用也是如此吗?
- 为什么内存有-7 MB?是因为作为数组列表实现的列表从堆中释放了吗?
- 无论是list还是dict,del x只能释放数据结构本身(我的意思是数组列表结构,或者dict结构),但是整数、对象引用可以标记为free,但不能返回给系统?
在这个例子中,我该如何释放 x 中的所有下划线列表?
Line # Mem usage Increment Line Contents
================================================
4 28.047 MiB 0.000 MiB @profile
5 def function():
6 248.008 MiB 219.961 MiB x = [list(range(10)) for _ in xrange(1000000)]
7 502.195 MiB 254.188 MiB y = copy.deepcopy(x)
8 494.562 MiB -7.633 MiB del x[:]
9 494.562 MiB 0.000 MiB return y