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

查看:21
本文介绍了如何检查 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 的东西,并返回对象使用的内存.

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 有一个很大的障碍,即对象通常包含对其他对象的引用.例如,字典包含字符串键和其他对象作为值.那些其他对象可能是共享的.由于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天全站免登陆