Note that there are some explanatory texts on larger screens.

plurals
  1. PODeep version of sys.getsizeof
    primarykey
    data
    text
    <p>I want to calculate the memory used by an object. <code>sys.getsizeof</code> is great, but is shallow (for example, called on a list, it would not include the memory taken by the list's elements).</p> <p>I'd like to write a generic "deep" version of <code>sys.getsizeof</code>. I understand there is some ambiguity in the definition of "deep"; I'm perfectly happy with the <a href="http://docs.python.org/3.4/library/copy.html" rel="noreferrer">definition followed by <code>copy.deepcopy</code></a>.</p> <p>Here's my first attempt:</p> <pre><code>def get_deep_sizeof(x, level=0, processed=None): if processed is None: # we're here only if this function is called by client code, not recursively processed = set() processed.add(id(x)) mem = sys.getsizeof(x) if isinstance(x, collections.Iterable) and not isinstance(x, str): for xx in x: if id(xx) in processed: continue mem += get_deep_sizeof(xx, level+1, processed) if isinstance(x, dict): mem += get_deep_sizeof(x[xx], level+1, processed) return mem </code></pre> <p>It suffers from two known problems, and an unknown number of unknown problems:</p> <ul> <li>I don't know how to traverse a generic container in a way that captures all the linked objects. Therefore, I iterated using <code>in</code>, and hard coded the case of dictionary (to include values, and not just the keys). Obviously, this will not work for other classes like dictionary.</li> <li>I had to hard code the exclusion of <code>str</code> (which is an iterable, and yet does not have links to any other objects). Again, this will break if there are more objects like that.</li> </ul> <p>I suspect that using <code>in</code> is not a good idea, but I'm not sure what else to do.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload