是否有适用于python2.7的内存分析器? [英] Is there a memory profiler for python2.7?

查看:80
本文介绍了是否有适用于python2.7的内存分析器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I needed to check the memory stats of objects I use in python.
I came across guppy and pysizer, but they are not available for python2.7.
Is there a memory profiler available for python 2.7?
If not is there a way I can do it myself?

推荐答案

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

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

这篇关于是否有适用于python2.7的内存分析器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆