Python3 基本类型在64位上的占用内存情况

本文分析了Python3在64位系统上基本类型如None、int、float、bool、str、tuple、list、set和dict占用的内存情况。通过`sys.getsizeof()`函数展示了不同类型的内存大小,并指出在64位系统中,int和float的内存消耗增加,特别是int的开销增大,而浮点数保持不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本类型占用的内存

  • 类型
  • # -*- 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值