Is there a reference for the memory size of Python data stucture on 32- and 64-bit platforms?
If not, this would be nice to have it on SO. The more exhaustive the better! So how many bytes are used by the following Python structures (depending on the len
and the content type when relevant)?
int
float
- reference
str
- unicode string
tuple
list
dict
set
array.array
numpy.array
deque
- new-style classes object
- old-style classes object
- ... and everything I am forgetting!
(For containers that keep only references to other objects, we obviously do not want to count the size of the item themselves, since it might be shared.)
Furthermore, is there a way to get the memory used by an object at runtime (recursively or not)?
I've been happily using pympler for such tasks. It's compatible with many versions of Python -- the
asizeof
module in particular goes back to 2.2!For example, using hughdbrown's example but with
from pympler import asizeof
at the start andprint asizeof.asizeof(v)
at the end, I see (system Python 2.5 on MacOSX 10.5):Clearly there is some approximation here, but I've found it very useful for footprint analysis and tuning.
Also you can use guppy module.
And:
The recommendation from an earlier question on this was to use sys.getsizeof(), quoting:
You could take this approach:
2012-09-30
python 2.7 (linux, 32-bit):
python 3.3 (linux, 32-bit)
2016-08-01
OSX, Python 2.7.10 (default, Oct 23 2015, 19:19:21) [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
When you use the dir([object]) built-in function, you can the sizeof built-in function.
These answers all collect shallow size information. I suspect that visitors to this question will end up here looking to answer the question, "How big is this complex object in memory?"
There's a great answer here: https://goshippo.com/blog/measure-real-size-any-python-object/
The punchline:
Used like so:
If you want to know Python's memory model more deeply, there's a great article here that has a similar "total size" snippet of code as part of a longer explanation: https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609
Try memory profiler. memory profiler