Get a Python object's memory size

vegaseat 3 Tallied Votes 522 Views Share

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
''' 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
'''
woooee 814 Nearly a Posting Maven

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
"""
Nils_1 0 Newbie Poster

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
Tcll 66 Posting Whiz in Training Featured Poster

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.