【发布时间】:2018-01-23 01:41:38
【问题描述】:
我最近遇到了this article关于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
与 deepcopy 相比,如果我使用复制,删除后似乎内存恢复到新创建 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只能释放数据结构本身(我的意思是数组list结构,或者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
【问题讨论】:
标签: python memory memory-management