How can I check the memory usage of objects in iPython?

前端 未结 4 466
萌比男神i
萌比男神i 2020-12-01 04:21

I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance:

In [         


        
4条回答
  •  孤城傲影
    2020-12-01 04:55

    Unfortunately this is not possible, but there are a number of ways of approximating the answer:

    1. for very simple objects (e.g. ints, strings, floats, doubles) which are represented more or less as simple C-language types you can simply calculate the number of bytes as with John Mulder's solution.

    2. For more complex objects a good approximation is to serialize the object to a string using cPickle.dumps. The length of the string is a good approximation of the amount of memory required to store an object.

    There is one big snag with solution 2, which is that objects usually contain references to other objects. For example a dict contains string-keys and other objects as values. Those other objects might be shared. Since pickle always tries to do a complete serialization of the object it will always over-estimate the amount of memory required to store an object.

提交回复
热议问题