simha simha - 1 year ago 125
Python Question

Is there a memory profiler for python2.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?

Answer Source

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
        total = sys.getsizeof(obj)
        if obj is None:
        elif isinstance(obj, (int, float, complex)):
        elif isinstance(obj, (list, tuple, range)):
            if isinstance(obj, (list, tuple)):
                total += sum(_sizeof(item, memo) for item in obj)
        elif isinstance(obj, str):
        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)
            raise TypeError('could not get size of {!r}'.format(obj))
        return total
    return _sizeof(variable, set())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download