欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-09-28 19:44:44
基本类型占用的内存 类型 # -*- 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 ......

基本类型占用的内存

  • 类型
  • # -*- 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