找出 Python 中的对象使用了多少内存 [英] Find out how much memory is being used by an object in Python

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

问题描述

您将如何确定对象使用了多少内存?我知道可以找出代码块使用了多少,而不是实例化对象(在其生命周期中的任何时间)使用了多少,这正是我想要的.

How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.

推荐答案

没有简单的方法可以找出 Python 对象的内存大小.您可能会发现的问题之一是 Python 对象(如列表和字典)可能引用其他 Python 对象(在这种情况下,您的大小是多少?包含每个对象大小的大小?).有一些与对象类型和垃圾收集相关的指针开销和内部结构.最后,一些 python 对象有不明显的行为.例如,大多数情况下,列表为比它们拥有的更多的对象保留空间;dicts 更加复杂,因为它们可以以不同的方式运行(它们对少量键有不同的实现,有时它们会过度分配条目).

There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).

有一个大量代码(还有一个更新了一大块代码) 以尽量接近内存中 python 对象的大小.

There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory.

您可能还想查看一些有关 PyObject 的旧描述(代表几乎所有 python 对象的内部 C 结构).

You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects).

这篇关于找出 Python 中的对象使用了多少内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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