Variable's memory size in Python [duplicate] Variable's memory size in Python [duplicate] python python

Variable's memory size in Python [duplicate]


Use sys.getsizeof to get the size of an object, in bytes.

>>> from sys import getsizeof>>> a = 42>>> getsizeof(a)12>>> a = 2**1000>>> getsizeof(a)146>>>

Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.


Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).

>>> import sys>>> sys.int_infosys.int_info(bits_per_digit=30, sizeof_digit=4)

Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get

>>> import math, sys>>> a=0>>> sys.getsizeof(a)24>>> a=2**100>>> sys.getsizeof(a)40>>> a=2**1000>>> sys.getsizeof(a)160>>> 24+4*math.ceil(100/30)40>>> 24+4*math.ceil(1000/30)160

There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.

If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).