010. Python的整形占多大内存?

示例代码

import sys
a = 0
print(a.__sizeof__())  # 24
print(sys.getsizeof(a)) # 24
  • 所以答案是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
  • 有点规律了,1073741824是什么鬼?它是2**30
  • 实际上,python的int类型就是动态的,每230增加4个字节**
  • 那下一个边界是?2**60!
print(sys.getsizeof(2**60))  # 36
  • 那其他类型呢?可以参考附录

sizeof()

  • 返回内存中的大小,单位字节
 |  __sizeof__(self, /)
 |      Returns size in memory, in bytes.

getsizeof()

  • 这是sys模块的一个方法
  • 在pycharm中你只能看到如下内容,不过大致也是返回对象的大小,单位是字节
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个字节

  • 代码大了之后,内存管理就显得非常重要了,现在仅作了解

附录

  • 对于其他类型,有人做了一些测试

  • 基于 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.
    
03-08 10:27