Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know bytes size of python object like arrays and dictionaries? - The simple way

I was looking for a easy way to know bytes size of arrays and dictionaries object, like

[ [1,2,3], [4,5,6] ] or { 1:{2:2} } 

Many topics say to use pylab, for example:

from pylab import *  A = array( [ [1,2,3], [4,5,6] ] ) A.nbytes 24 

But, what about dictionaries? I saw lot of answers proposing to use pysize or heapy. An easy answer is given by Torsten Marek in this link: Which Python memory profiler is recommended?, but I haven't a clear interpretation about the output because the number of bytes didn't match.

Pysize seems to be more complicated and I haven't a clear idea about how to use it yet.

Given the simplicity of size calculation that I want to perform (no classes nor complex structures), any idea about a easy way to get a approximate estimation of memory usage of this kind of objects?

Kind regards.

like image 907
crandrades Avatar asked Nov 23 '12 14:11

crandrades


People also ask

How do you calculate byte size in Python?

In python, the usage of sys. getsizeof() can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes.

How do you check the memory size of an object in Python?

In Python, the most basic function for measuring the size of an object in memory is sys. getsizeof() .

How do you check the size of a dictionary in Python?

The len() function is widely used to determine the size of objects in Python. In our case, passing a dictionary object to this function will return the size of the dictionary i.e. the number of key-value pairs present in the dictionary.

How much memory does Python dictionary use?

This sums up to at least 12 bytes on a 32bit machine and 24 bytes on a 64bit machine. The dictionary starts with 8 empty buckets. This is then resized by doubling the number of entries whenever its capacity is reached.


1 Answers

There's:

>>> import sys >>> sys.getsizeof([1,2, 3]) 96 >>> a = [] >>> sys.getsizeof(a) 72 >>> a = [1] >>> sys.getsizeof(a) 80 

But I wouldn't say it's that reliable, as Python has overhead for each object, and there are objects that contain nothing but references to other objects, so it's not quite the same as in C and other languages.

Have a read of the docs on sys.getsizeof and go from there I guess.

like image 151
Jon Clements Avatar answered Sep 22 '22 08:09

Jon Clements