views:

69

answers:

2

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.

+3  A: 

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. I don't believe that's recursive, although the documentation doesn't say explicitly.

David Zaslavsky
+1. For what it's worth, it's not recursive.
Daniel Stutzbach
Thanks. This works for me!
Wai Yip Tung
A: 

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__

gnibbler