如何检查iPython中对象的内存使用情况? [英] How can I check the memory usage of objects in iPython?

查看:286
本文介绍了如何检查iPython中对象的内存使用情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用iPython来运行我的代码。我想知道是否有任何模块或命令可以让我检查一个对象的内存使用情况。例如:

I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance:

In [1]: a = range(10000)
In [2]: %memusage a
Out[2]: 1MB

%memusage< ; object> 并返回对象使用的内存。

Something like %memusage <object> and return the memory used by the object.

重复


了解Python中对象使用了多少内存


推荐答案

不幸的是,这是不可能的,但有很多方法可以接近答案:

Unfortunately this is not possible, but there are a number of ways of approximating the answer:


  1. 对于非常简单的对象(例如整数,字符串,浮点数,双精度数),它们或多或少表示为简单的C语言类型,您可以简单地计算字节数,如 John Mulder的解决方案

对于更复杂的对象一个很好的近似是使用cPickle.dumps将对象序列化为一个字符串。字符串的长度很好地近似了存储对象所需的内存量。

For more complex objects a good approximation is to serialize the object to a string using cPickle.dumps. The length of the string is a good approximation of the amount of memory required to store an object.

解决方案2有一个很大的障碍,即对象通常包含对其他对象的引用。例如,dict包含字符串键和其他对象作为值。那些其他对象可能是共享的。由于pickle总是尝试对对象进行完整的序列化,因此它总是会高估存储对象所需的内存量。

There is one big snag with solution 2, which is that objects usually contain references to other objects. For example a dict contains string-keys and other objects as values. Those other objects might be shared. Since pickle always tries to do a complete serialization of the object it will always over-estimate the amount of memory required to store an object.

这篇关于如何检查iPython中对象的内存使用情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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