Ros*_*oss 34 python memory ipython
我正在使用iPython来运行我的代码.我想知道是否有任何模块或命令可以让我检查一个对象的内存使用情况.例如:
In [1]: a = range(10000)
In [2]: %memusage a
Out[2]: 1MB
Run Code Online (Sandbox Code Playgroud)
类似于%memusage <object>并返回对象使用的内存.
重复
Sal*_*ley 52
不幸的是,这是不可能的,但有很多方法可以接近答案:
对于非常简单的对象(例如整数,字符串,浮点数,双精度数),它们或多或少地表示为简单的C语言类型,您可以像John Mulder的解决方案一样简单地计算字节数.
对于更复杂的对象,一个很好的近似是使用cPickle.dumps将对象序列化为字符串.字符串的长度很好地近似了存储对象所需的内存量.
解决方案2有一个很大的障碍,即对象通常包含对其他对象的引用.例如,dict包含字符串键和其他对象作为值.那些其他对象可能是共享的.由于pickle总是尝试对对象进行完整的序列化,因此它总是高估存储对象所需的内存量.
HoW*_*Wil 20
如果您使用的是numpy数组,那么您可以使用该属性ndarray.nbytes来评估其在内存中的大小:
from pylab import *
d = array([2,3,4,5])
d.nbytes
#Output: 32
Run Code Online (Sandbox Code Playgroud)
Joh*_*der 14
更新:这是另一个可能更全面的估计python对象大小的方法.
这是一个解决类似问题 的线索
提出的解决方案是编写自己的...使用已知的基元大小,python的对象开销和内置容器类型的大小的一些估计.
由于代码不长,这里是它的直接副本:
def sizeof(obj):
"""APPROXIMATE memory taken by some Python objects in
the current 32-bit CPython implementation.
Excludes the space used by items in containers; does not
take into account overhead of memory allocation from the
operating system, or over-allocation by lists and dicts.
"""
T = type(obj)
if T is int:
kind = "fixed"
container = False
size = 4
elif T is list or T is tuple:
kind = "variable"
container = True
size = 4*len(obj)
elif T is dict:
kind = "variable"
container = True
size = 144
if len(obj) > 8:
size += 12*(len(obj)-8)
elif T is str:
kind = "variable"
container = False
size = len(obj) + 1
else:
raise TypeError("don't know about this kind of object")
if kind == "fixed":
overhead = 8
else: # "variable"
overhead = 12
if container:
garbage_collector = 8
else:
garbage_collector = 0
malloc = 8 # in most cases
size = size + overhead + garbage_collector + malloc
# Round to nearest multiple of 8 bytes
x = size % 8
if x != 0:
size += 8-x
size = (size + 8)
return size
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42935 次 |
| 最近记录: |