Get a Python object's memory size UserPageVisits:488 active 80 80 DaniWeb 561 60 2013-12-16T14:53:32+00:00 https://www.daniweb.com/programming/software-development/code/465921/get-a-python-object-s-memory-size

Get a Python object's memory size

vegaseat

Shows you how to get a Python object's memory size. Notice that there can be a difference between Python versions.

Tcll commented: definately useful for checking memory-hungry algorithms and optimizing them =D +2
488 Views
About the Author

Scientist

code snippet
''' object_size.py
get the size of a Python object in memory
tested with Python27 and Python33  by  vegaseat  22oct2013
'''

import sys

mytuple = ()
mylist = []
mydict = {}
mystr = "" 
 
print("Size of empty tuple = {}".format(sys.getsizeof(mytuple)))
print("Size of empty list = {}".format(sys.getsizeof(mylist))) 
print("Size of empty dictionary = {}".format(sys.getsizeof(mydict))) 
print("Size of empty string = {}".format(sys.getsizeof(mystr))) 

''' 
result (Python27, 32 bit version) ...
Size of empty tuple = 28
Size of empty list = 36
Size of empty dictionary = 140
Size of empty string = 21

result (Python33, 32 bit version) ...
Size of empty tuple = 28
Size of empty list = 36
Size of empty dictionary = 148
Size of empty string = 25
'''

64 bit, Python 2.7 is predictably twice the memory, except for the string???

"""
Size of empty tuple = 56
Size of empty list = 72
Size of empty dictionary = 280
Size of empty string = 37
"""

64 bit, Python 3.2.3:

Size of empty tuple = 28
Size of empty list = 36
Size of empty dictionary = 140
Size of empty string = 30

might I suggest checking array.array() and bytearray() :)

or I will when I stop being lazy XD

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.