How do I profile memory usage in Python?

前端 未结 8 565
无人及你
无人及你 2020-11-22 09:50

I\'ve recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.

I\'m already f

8条回答
  •  无人及你
    2020-11-22 10:24

    If you only want to look at the memory usage of an object, (answer to other question)

    There is a module called Pympler which contains the asizeof module.

    Use as follows:

    from pympler import asizeof
    asizeof.asizeof(my_object)
    

    Unlike sys.getsizeof, it works for your self-created objects.

    >>> asizeof.asizeof(tuple('bcd'))
    200
    >>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'})
    400
    >>> asizeof.asizeof({})
    280
    >>> asizeof.asizeof({'foo':'bar'})
    360
    >>> asizeof.asizeof('foo')
    40
    >>> asizeof.asizeof(Bar())
    352
    >>> asizeof.asizeof(Bar().__dict__)
    280
    
    >>> help(asizeof.asizeof)
    Help on function asizeof in module pympler.asizeof:
    
    asizeof(*objs, **opts)
        Return the combined size in bytes of all objects passed as positional arguments.
    

提交回复
热议问题