如何在Python中获得对象在内存中占用的大小?
当前回答
对于numpy数组,getsizeof不起作用-对我来说,它总是出于某种原因返回40:
from pylab import *
from sys import getsizeof
A = rand(10)
B = rand(10000)
然后(在ipython中):
In [64]: getsizeof(A)
Out[64]: 40
In [65]: getsizeof(B)
Out[65]: 40
不过令人高兴的是,:
In [66]: A.nbytes
Out[66]: 80
In [67]: B.nbytes
Out[67]: 80000
其他回答
使用以下函数获取python对象的实际大小:
import sys
import gc
def actualsize(input_obj):
memory_size = 0
ids = set()
objects = [input_obj]
while objects:
new = []
for obj in objects:
if id(obj) not in ids:
ids.add(id(obj))
memory_size += sys.getsizeof(obj)
new.append(obj)
objects = gc.get_referents(*new)
return memory_size
actualsize([1, 2, [3, 4, 5, 1]])
参考:https://towardsdatascience.com/the-strange-size-of-python-objects-in-memory-ce87bdfbb97f
这可能不是最相关的答案,但我只对对象存储和检索感兴趣。因此将对象转储为pickle并检查pickle的大小就足够了
Python 3.8(2019年第一季度)将改变sys. js的一些结果。getsizeof, Raymond Hettinger在此宣布:
Python容器在64位版本上要小8个字节。
tuple () 48 -> 40
list [] 64 ->56
set() 224 -> 216
dict {} 240 -> 232
这是在议题33597和稻田直树(甲烷)围绕紧凑型PyGC_Head和PR 7043的工作之后
这个想法将PyGC_Head大小减少到两个单词。 目前,PyGC_Head包含三个单词;Gc_prev, gc_next和gc_refcnt。 收集时使用Gc_refcnt,用于尝试删除。 Gc_prev用于跟踪和取消跟踪。 因此,如果我们可以在试删除时避免跟踪/取消跟踪,gc_prev和gc_refcnt可以共享相同的内存空间。
参见commit d5c875b:
从PyGC_Head中移除一个Py_ssize_t成员。 所有GC跟踪的对象(例如元组,列表,dict)大小减少4或8字节。
如果性能不是问题,最简单的解决方案是pickle和测量:
import pickle
data = ...
len(pickle.dumps(data))
用系统就行了。sys模块中定义的Getsizeof函数。
sys.getsizeof(object[, default]): Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific. Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to. The default argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a TypeError. getsizeof calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector. See recursive sizeof recipe for an example of using getsizeof() recursively to find the size of containers and all their contents.
python 3.0中的用法示例:
>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
24
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48
如果你在python < 2.6并且没有sys. exe。Getsizeof可以使用这个扩展模块。但从来没用过。
推荐文章
- 把if-elif-else语句放在一行中?
- 我如何结合两个数据框架?
- 如何计数列表中唯一值的出现
- 在JSON键名中哪些字符是有效的/无效的?
- 为什么Pycharm的检查人员抱怨“d ={}”?
- 如何JSON序列化集?
- 大概的成本访问各种缓存和主存储器?
- 高速缓存线是如何工作的?
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么