20

How do I find out the memory size of a Python data structure? I'm looking for something like:

sizeof({1:'hello', 2:'world'})

It is great if it counts every thing recursively. But even a basic non-recursive result helps. Basically I want to get a sense of various implementation options like tuple v.s. list v.s. class in terms of memory footprint. It matters because I'm planning to have millions of object instantiated.

My current dev platform is CPython 2.6.

2
  • That's going to be a really slow program, unless you have a lot of memory. Plus the size of the lookup table is going to be pretty huge (millions of objects?). Just sayin' Commented Aug 12, 2010 at 20:06
  • 1
    namedtuple is a good alternative to using classes as the space required by each instance is the same as a tuple. If you have a lot of instances of one class, you should look into __slots__ Commented Aug 12, 2010 at 20:51

1 Answer 1

29

Have a look at the sys.getsizeof function. According to the documentation, it returns the size of an object in bytes, as given by the object's __sizeof__ method.

As Daniel pointed out in a comment, it's not recursive; it only counts bytes occupied by the object itself, not other objects it refers to. This recipe for a recursive computation is linked to by the Python 3 documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

This version works well for Python 2: gist.github.com/durden/0b93cfe4027761e17e69c48f9d5c4118

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.