对于看似不同的列表,getsizeof返回相同的值 [英] getsizeof returns the same value for seemingly different lists
问题描述
我有以下二维位图:
num = 521
arr = [i == '1' for i in bin(num)[2:].zfill(n*n)]
board = [arr[n*i:n*i+n] for i in xrange(n)]
出于好奇,我想检查一下,如果它将使用整数而不是布尔值,它将占用多少空间.所以我用sys.getsizeof(board)
检查了当前大小,并得到了 104
Just for curiosity I wanted to check how much more space will it take, if it will have integers instead of booleans. So I checked the current size with sys.getsizeof(board)
and got 104
那之后我修改了
arr = [int(i) for i in bin(num)[2:].zfill(n*n)]
,但仍然获得 104
然后我决定看看仅凭字符串我能得到多少:
Then I decided to see how much will I get with just strings:
arr = [i for i in bin(num)[2:].zfill(n*n)]
,仍然显示 104
这看起来很奇怪,因为我希望字符串列表比布尔值浪费更多的内存.
This looks strange, because I expected list of lists of strings to waste way more memory than just booleans.
显然,我缺少有关getsizeof如何计算大小的信息.谁能解释我为什么会得到这样的结果.
Apparently I am missing something about how the getsizeof calculates the size. Can anyone explain me why I get such results.
P.S.感谢zehnpard的回答,我发现我可以使用sum(sys.getsizeof(i) for line in board for i in line)
来近似计算内存(很可能不会计算列表,这对我来说并不重要).现在,我看到了string和int/bool的数字差异(int和boolean的数字没有差异)
P.S. thanks to zehnpard's answer, I see that I can use sum(sys.getsizeof(i) for line in board for i in line)
to approximately count the memory (most probably it will not count the lists, which is not that much important for me). Now I see the difference in numbers for string and int/bool (no difference for int and boolean)
推荐答案
文档sys模块,因为Python 3.4非常明确:
The docs for the sys module since Python 3.4 is pretty explicit:
仅考虑直接归因于对象的内存消耗,而不考虑它所引用的对象的内存消耗.
Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.
鉴于Python列表实际上是指向其他Python对象的指针数组,因此Python列表包含的元素数量将影响其在内存中的大小(更多的指针),但包含的对象类型则不会(在内存方面,它们不是没有包含在列表中,只是指向).
Given that Python lists are effectively arrays of pointers to other Python objects, the number of elements a Python list contains will influence its size in memory (more pointers) but the type of objects contained will not (memory-wise, they aren't contained in the list, just pointed at).
要获取容器中所有项目的大小,您需要一个递归解决方案,并且文档有帮助地提供了一个指向activestate配方的链接. http://code.activestate.com/recipes/577504/
To get the size of all items in a container, you need a recursive solution, and the docs helpfully provide a link to an activestate recipe. http://code.activestate.com/recipes/577504/
鉴于此食谱是针对Python 2.x的,所以我确信这种行为始终是标准的,并且从3.4开始就在文档中得到了明确提及.
Given that this recipe is for Python 2.x, I'm sure this behavior was always standard, and got explicitly mentioned in the docs since 3.4 onwards.
这篇关于对于看似不同的列表,getsizeof返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!