基本类型占用的内存

  • 类型
  • # -*- coding: utf-8 -*- 
    # @Time     : 2019-12-19 11:16
    # @Author   : binger
    
    import sys
    
    a = None
    b = 1000.2311
    c = 1000
    d = True
    e = ""
    f = ()
    g = []
    h = set([])
    i = {}
    
    print(" %s size is %d " % (type(a), sys.getsizeof(a)))
    print(" %s size is %d " % (type(b), sys.getsizeof(b)))
    print(" %s size is %d " % (type(c), sys.getsizeof(c)))
    print(" %s size is %d " % (type(d), sys.getsizeof(d)))
    print(" %s size is %d " % (type(e), sys.getsizeof(e)), sys.getsizeof("12"))
    print(" %s size is %d " % (type(f), sys.getsizeof(f)), sys.getsizeof((1,)))
    print(" %s size is %d " % (type(g), sys.getsizeof(g)), sys.getsizeof([1, ]))
    print(" %s size is %d " % (type(h), sys.getsizeof(h)), sys.getsizeof(set([1, ])))
    print(" %s size is %d " % (type(i), sys.getsizeof(i)), sys.getsizeof({1: 1}))
  • 结果:
    内存大小排行: None < float < int = bool < str < tuple < list < set < dict
  •  <class 'NoneType'> size is 16 Byte
     <class 'float'> size is 24 Byte
     <class 'int'> size is 28 Byte
     <class 'bool'> size is 28 Byte
     <class 'str'> size is 49  Byte 51
     <class 'tuple'> size is 56  Byte 64
     <class 'list'> size is 72  Byte 80
     <class 'set'> size is 232  Byte 232
     <class 'dict'> size is 248  Byte 248

分析:

  • int和float:
    • int和float的64位系统中的 Python 3 内存消耗:int > float
    • 间接费用(PyObject_HEAD)增加了一倍,但整数的大小从32位变为64位,而浮点数(双精度)的大小仍为64:
    • 32位
      int:开销= 10字节,值= 4字节
      float:开销= 8字节,value = 8字节
      
      64位
      int:开销= 20字节,值= 8字节
      float:开销= 16个字节,值= 8个字节
    • 64位 Python 2 中 int 和 float 均为 24B。但是 int 不包含 long类型(28B)
  • 字典与链表
from bintrees import bintree
import uuid, time, sys
import random


def create_uuid(msg):
    src_uuid = uuid.uuid4()
    name = "{}{}".format(time.time(), msg)
    return uuid.uuid3(src_uuid, name=name).hex


a = {create_uuid(i): random.randint(0, 10) for i in range(2000)}
b = {i: i for i in range(2000)}
ring = bintree.BinaryTree()
c = [ring.insert(create_uuid(i), i) for i in range(2000)]
ring2 = bintree.BinaryTree()
d = [ring2.insert(i, i) for i in range(2000)]

print("字典1", sys.getsizeof(a))
print("字典2", sys.getsizeof(b))
print("二叉树:", sys.getsizeof(c))
print("二叉树:", sys.getsizeof(d))
    • 结果:
字典1 73832
字典2 73832
二叉树: 16568
二叉树: 16568
12-20 06:42