Python结构的内存大小 [英] In-memory size of a Python structure

查看:129
本文介绍了Python结构的内存大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有关于32位和64位平台上Python数据结构的内存大小的参考?

Is there a reference for the memory size of Python data stucture on 32- and 64-bit platforms?

如果没有,那么在SO上安装它会很好.越详尽越好!那么以下Python结构使用了多少字节(取决于len和相关的内容类型)?

If not, this would be nice to have it on SO. The more exhaustive the better! So how many bytes are used by the following Python structures (depending on the len and the content type when relevant)?

  • int
  • float
  • 参考
  • str
  • unicode字符串
  • tuple
  • list
  • dict
  • set
  • array.array
  • numpy.array
  • deque
  • 新型类对象
  • 老式类对象
  • ...还有我忘记的一切!
  • int
  • float
  • reference
  • str
  • unicode string
  • tuple
  • list
  • dict
  • set
  • array.array
  • numpy.array
  • deque
  • new-style classes object
  • old-style classes object
  • ... and everything I am forgetting!

(对于仅保留对其他对象的引用的容器,我们显然不想计算项目本身的大小,因为它可能是共享的.)

(For containers that keep only references to other objects, we obviously do not want to count the size of the item themselves, since it might be shared.)

此外,是否有一种方法可以获取对象在运行时使用的内存(递归与否)?

Furthermore, is there a way to get the memory used by an object at runtime (recursively or not)?

推荐答案

来自

The recommendation from an earlier question on this was to use sys.getsizeof(), quoting:

>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
14
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48

您可以采用这种方法:

>>> import sys
>>> import decimal
>>> 
>>> d = {
...     "int": 0,
...     "float": 0.0,
...     "dict": dict(),
...     "set": set(),
...     "tuple": tuple(),
...     "list": list(),
...     "str": "a",
...     "unicode": u"a",
...     "decimal": decimal.Decimal(0),
...     "object": object(),
... }
>>> for k, v in sorted(d.iteritems()):
...     print k, sys.getsizeof(v)
...
decimal 40
dict 140
float 16
int 12
list 36
object 8
set 116
str 25
tuple 28
unicode 28


2012-09-30


2012-09-30

python 2.7(Linux,32位):

python 2.7 (linux, 32-bit):

decimal 36
dict 136
float 16
int 12
list 32
object 8
set 112
str 22
tuple 24
unicode 32

python 3.3(Linux,32位)

python 3.3 (linux, 32-bit)

decimal 52
dict 144
float 16
int 14
list 32
object 8
set 112
str 26
tuple 24
unicode 26


2016-08-01


2016-08-01

OSX,Python 2.7.10(默认值,2015年10月23日,19:19:21)[darwin上的[GCC 4.2.1兼容Apple LLVM 7.0.0(clang-700.0.59.5)]

OSX, Python 2.7.10 (default, Oct 23 2015, 19:19:21) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin

decimal 80
dict 280
float 24
int 24
list 72
object 16
set 232
str 38
tuple 56
unicode 52

这篇关于Python结构的内存大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆