有适用于python2.7的内存分析工具吗?

4 投票
4 回答
4692 浏览
提问于 2025-04-16 08:23

我想查看我在Python中使用的对象的内存使用情况。
我发现了guppy和pysizer这两个工具,但它们不支持Python 2.7。
有没有适合Python 2.7的内存分析工具?
如果没有,我自己能不能实现这个功能?

4 个回答

1

我不知道有没有适用于Python 2.7的性能分析工具,不过你可以看看下面这个函数,它已经被加入到sys模块里,可能能帮你自己实现这个功能。

“一个新函数getsizeof(),可以获取一个Python对象所占用的内存大小,单位是字节。内置对象会返回正确的结果;而第三方扩展可能不会,但可以定义一个__sizeof__()方法来返回对象的大小。”

这里有一些在线文档的链接,可以了解更多信息:

    Python 2.6的新特性
    27.1. sys模块 — 系统特定的参数和函数

2

这里有一个适用于Python 2.7的工具:Pympler包

2

你可以尝试把下面的代码调整一下,让它更适合你的具体情况,并且支持你所用的数据类型:

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())

撰写回答