Python memory management Help

Integers

Integers have a memory length of 24 bytes for the object itself and a further 32 bits for the value. The usage of the 32 bits can be seen in my page on IEEE 574 implementation.

As numbers increase in size they still take a total memory allocation is 32 bytes.

from pympler import asizeof import sys a = 10 print(f'{a} has a bit length of {a.bit_length()} bits.') print(f'{a} has a sys size of {sys.getsizeof(a)} bytes.') print(f'{a} has an asizeof {asizeof.asizeof(a)} bytes.') a = 9_999_999_999_999 print(f'{a} has a bit length of {a.bit_length()} bits.') print(f'{a} has a sys size of {sys.getsizeof(a)} bytes.') print(f'{a} has an asizeof {asizeof.asizeof(a)} bytes.')

Output

10 has a bit length of 4 bits. 10 has a sys size of 28 bytes. 10 has an asizeof 32 bytes. 9999999999999 has a bit length of 44 bits. 9999999999999 has a sys size of 32 bytes. 9999999999999 has an asizeof 32 bytes.

Integers below 1_073_741_824 will require 28 bytes for the int object (which includes the memory address) and a further 4 bytes for the actual value stored in memory as a 32 bit signed integer (IEEE 574). If we restrict our interest in primes to those below ~109 we can assume every integer we are storing will require 32 bytes of memory.

Knowing this means we can interrogate the size of a list of integers.

Last modified: 03 July 2024