且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有适用于python2.7的内存分析器?

更新时间:2023-02-16 15:38:34

您可能想尝试将以下代码修改为适合您的特定情况并支持您的数据类型:

You might want to try adapting the following code to your specific situation and support your data types:

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