【问题标题】:In-memory size of a Python structurePython 结构的内存大小
【发布时间】:2010-11-22 19:41:50
【问题描述】:

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

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

  • int
  • float
  • 参考
  • str
  • unicode 字符串
  • tuple
  • list
  • dict
  • set
  • array.array
  • numpy.array
  • deque
  • 新型类对象
  • 旧式类对象
  • ...以及我忘记的一切!

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

此外,有没有办法在运行时(递归或不递归)获取对象使用的内存?

【问题讨论】:

标签: python memory memory-footprint


【解决方案1】:

an earlier question 对此的建议是使用sys.getsizeof(),引用:

>>> 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

python 2.7(Linux,32 位):

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 位)

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

2016-08-01

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

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

【讨论】:

  • 谢谢,对第二个问题的欺骗感到抱歉...太糟糕了,我使用的是 2.5 而不是 2.6...
  • 我忘了我有一个虚拟盒子,上面有一个最近的 ubuntu!这很奇怪,sys.getsizeof(dict) 对我来说是 136(python 2.6 在 kubuntu vm 上运行,由 OS X 托管,所以我不确定)
  • @LeMiz: 对我来说 (Python 2.6, Windows XP SP3), sys.getsizeof(dict) -> 436; sys.getsizeof(dict()) -> 140
  • LeMiz-Kubuntu:python2.6 Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 输入“帮助”、“版权” 、“学分”或“许可”以获取更多信息。 >>> 导入系统 >>> sys.getsizeof(dict) 436 >>> sys.getsizeof(dict()) 136
  • 为了保持一致性,值不应该是00.0''u''吗?
【解决方案2】:

这些答案都收集了浅层尺寸信息。我怀疑这个问题的访问者最终会在这里回答这个问题,“这个复杂的对象在内存中有多大?”

这里有一个很好的答案:https://goshippo.com/blog/measure-real-size-any-python-object/

妙语:

import sys

def get_size(obj, seen=None):
    """Recursively finds size of objects"""
    size = sys.getsizeof(obj)
    if seen is None:
        seen = set()
    obj_id = id(obj)
    if obj_id in seen:
        return 0
    # Important mark as seen *before* entering recursion to gracefully handle
    # self-referential objects
    seen.add(obj_id)
    if isinstance(obj, dict):
        size += sum([get_size(v, seen) for v in obj.values()])
        size += sum([get_size(k, seen) for k in obj.keys()])
    elif hasattr(obj, '__dict__'):
        size += get_size(obj.__dict__, seen)
    elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
        size += sum([get_size(i, seen) for i in obj])
    return size

这样使用:

In [1]: get_size(1)
Out[1]: 24

In [2]: get_size([1])
Out[2]: 104

In [3]: get_size([[1]])
Out[3]: 184

如果您想更深入地了解 Python 的内存模型,这里有一篇很棒的文章,其中有类似的“总大小”sn-p 代码作为更长解释的一部分:https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609

【讨论】:

  • 所以这应该产生例如包含多个数组和/或其他字典的字典所使用的内存总量?
  • @CharlyEmpereur-mot 是的。
  • 很好的答案。但是,它似乎不适用于已编译的 cython 对象。在我的情况下,此方法返回 96 以获取指向内存中 cython 对象的指针
【解决方案3】:

我一直很乐意使用pympler 来完成此类任务。它与许多版本的 Python 兼容——特别是 asizeof 模块可以追溯到 2.2!

例如,使用hughdbrown的示例,但以from pympler import asizeof开头和print asizeof.asizeof(v)结尾,我看到(MacOSX 10.5上的系统Python 2.5):

$ python pymp.py 
set 120
unicode 32
tuple 32
int 16
decimal 152
float 16
list 40
object 0
dict 144
str 32

显然这里有一些近似值,但我发现它对于足迹分析和调整非常有用。

【讨论】:

  • 一些好奇心:你们中的大多数人的数字都高 4;对象为 0;十进制大约是您估计的 4 倍。
  • 是的。 “4 更高”实际上大部分看起来像“四舍五入到 8 的倍数”,我认为这对于 malloc 在这里的行为方式是正确的。不知道为什么小数会如此失真(在 2.6 上也有 pympler)。
  • 其实应该使用 pymler.asizeof.flatsize() 来获得与 sys.getsizeof() 类似的功能。您还可以使用一个 align= 参数(正如 Alex 指出的那样,默认情况下为 8)。
  • @AlexMartelli 嗨,亚历克斯! .. 为什么 python 中 char 的最小大小是 25 字节。 >>> getsizeof('a') 提供25>>> getsizeof('ab') 提供26 `
  • 我想大小是以字节为单位的,但为什么它没有写在任何地方,即使在 pythonhosted.org/Pymler
【解决方案4】:

试试内存分析器。 memory profiler

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

【讨论】:

  • 精度似乎是 1/100MB,即 10.24 字节。这对于宏观分析来说很好,但我怀疑这种精度是否会导致问题中提出的数据结构的准确比较。
【解决方案5】:

您也可以使用guppy 模块。

>>> from guppy import hpy; hp=hpy()
>>> hp.heap()
Partition of a set of 25853 objects. Total size = 3320992 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0  11731  45   929072  28    929072  28 str
     1   5832  23   469760  14   1398832  42 tuple
     2    324   1   277728   8   1676560  50 dict (no owner)
     3     70   0   216976   7   1893536  57 dict of module
     4    199   1   210856   6   2104392  63 dict of type
     5   1627   6   208256   6   2312648  70 types.CodeType
     6   1592   6   191040   6   2503688  75 function
     7    199   1   177008   5   2680696  81 type
     8    124   0   135328   4   2816024  85 dict of class
     9   1045   4    83600   3   2899624  87 __builtin__.wrapper_descriptor
<90 more rows. Type e.g. '_.more' to view.>

还有:

>>> hp.iso(1, [1], "1", (1,), {1:1}, None)
Partition of a set of 6 objects. Total size = 560 bytes.
 Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
     0      1  17      280  50       280  50 dict (no owner)
     1      1  17      136  24       416  74 list
     2      1  17       64  11       480  86 tuple
     3      1  17       40   7       520  93 str
     4      1  17       24   4       544  97 int
     5      1  17       16   3       560 100 types.NoneType

【讨论】:

    【解决方案6】:

    也可以使用 Python 标准库中的 tracemalloc 模块。它似乎适用于用 C 实现类的对象(例如,与 Pymler 不同)。

    【讨论】:

      【解决方案7】:

      当你使用dir([object])内置函数时,可以得到内置函数的__sizeof__

      >>> a = -1
      >>> a.__sizeof__()
      24
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        • 2021-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多