import sys
a = 0
print(a.__sizeof__()) # 24
print(sys.getsizeof(a)) # 24
import sys
b = 1
print(b.__sizeof__()) # 28
print(sys.getsizeof(b)) # 28
import sys
c = 3
print(c.__sizeof__()) # 28
print(sys.getsizeof(c)) # 28
import sys
d = 1073741823
e = 1073741824
print(d.__sizeof__()) # 28
print(sys.getsizeof(e)) # 32
print(sys.getsizeof(2**60)) # 36
| __sizeof__(self, /)
| Returns size in memory, in bytes.
def getsizeof(p_object, default): # real signature unknown; restored from __doc__
"""
getsizeof(object, default) -> int
Return the size of object in bytes.
"""
return 0
2个貌似一样
其实不然
b = []
print(b.__sizeof__()) # 40
print(sys.getsizeof(b)) # 56 不一样(我在jupyter中执行的结果) # 如果你在pycharm中执行可能此处是 64
import sys
l = []
w =[1, 2]
x =[4, 5, 7, 9]
y =[2, 8, 6, 56, 45, 89, 88]
print('sizeof:%d,getsize:%d' %(l.__sizeof__(),sys.getsizeof(l)))
print('sizeof:%d,getsize:%d' %(w.__sizeof__(),sys.getsizeof(w)))
print('sizeof:%d,getsize:%d' %(x.__sizeof__(),sys.getsizeof(x)))
# sizeof:40,getsize:64 # 此处就是在pycharm中执行的
# sizeof:56,getsize:80
# sizeof:72,getsize:96
getsizeof() 方法调用__sizeof__
方法,但同时会附带一些额外的GC操作(arbage collector overhead). 因此前者的大小比后者要大一些
列表初始化的时候是40,每加一个元素是8个字节
代码大了之后,内存管理就显得非常重要了,现在仅作了解
https://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python
对于其他类型,有人做了一些测试
基于 64-bit Python 3.6,使用Anaconda
Empty
Bytes type scaling notes
28 int +4 bytes about every 30 powers of 2
37 bytes +1 byte per additional byte
49 str +1-4 per additional character (depending on max width)
48 tuple +8 per additional item
64 list +8 for each additional
224 set 5th increases to 736; 21nd, 2272; 85th, 8416; 341, 32992
240 dict 6th increases to 368; 22nd, 1184; 43rd, 2280; 86th, 4704; 171st, 9320
136 func def does not include default args and other attrs
1056 class def no slots
56 class inst has a __dict__ attr, same scaling as dict above
888 class def with slots
16 __slots__ seems to store in mutable tuple-like structure
first slot grows to 48, and so on.