gpt4 book ai didi

python - python2.7有内存分析器吗?

转载 作者:太空狗 更新时间:2023-10-30 01:10:23 25 4
gpt4 key购买 nike

我需要检查我在 python 中使用的对象的内存统计信息。
我遇到了 guppy 和 pysizer,但它们不适用于 python2.7。
是否有适用于 python 2.7 的内存分析器?
如果没有,我可以自己做吗?

最佳答案

您可能想尝试根据您的具体情况调整以下代码并支持您的数据类型:

import sys


def sizeof(variable):
def _sizeof(obj, memo):
address = id(obj)
if address in memo:
return 0
memo.add(address)
total = sys.getsizeof(obj)
if obj is None:
pass
elif isinstance(obj, (int, float, complex)):
pass
elif isinstance(obj, (list, tuple, range)):
if isinstance(obj, (list, tuple)):
total += sum(_sizeof(item, memo) for item in obj)
elif isinstance(obj, str):
pass
elif isinstance(obj, (bytes, bytearray, memoryview)):
if isinstance(obj, memoryview):
total += _sizeof(obj.obj, memo)
elif isinstance(obj, (set, frozenset)):
total += sum(_sizeof(item, memo) for item in obj)
elif isinstance(obj, dict):
total += sum(_sizeof(key, memo) + _sizeof(value, memo)
for key, value in obj.items())
elif hasattr(obj, '__slots__'):
for name in obj.__slots__:
total += _sizeof(getattr(obj, name, obj), memo)
elif hasattr(obj, '__dict__'):
total += _sizeof(obj.__dict__, memo)
else:
raise TypeError('could not get size of {!r}'.format(obj))
return total
return _sizeof(variable, set())

关于python - python2.7有内存分析器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4416654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com