Reputation: 4644
I am not looking for a constant recording the maximum value representable with an int
; I am looking to find out the maximum amount of memory that an int
can occupy. Consider the following code:
import sys
def print_and_execute(*args):
for s in args:
print(s, end = " == ")
r = eval(s)
print(r)
return
print_and_execute("type(5) ")
print_and_execute("sys.getsizeof(5)")
i = int()
print_and_execute("i")
print_and_execute("sys.getsizeof(i)")
i = 2937
print_and_execute("i")
print_and_execute("sys.getsizeof(i)")
print_and_execute("sys.maxsize")
print_and_execute("sys.getsizeof(sys.maxsize)")
For my particular machine, the output is:
type(5) == <class 'int'>
sys.getsizeof(5) == 28
i == 0
sys.getsizeof(i) == 24
i == 2937
sys.getsizeof(i) == 28
sys.maxsize == 9223372036854775807
sys.getsizeof(sys.maxsize) == 36
Apparently, some int
s are 24 bytes long, others are 28, still others use 36. How many bytes are required to hold an int
of any size?
Upvotes: 0
Views: 433
Reputation: 160397
How many bytes are required to hold any size
int
?
As many as are required. There's no limit on the size of int
s, they are of arbitrary size as their documentation states.*
sys.maxsize
does not represent the maximum size of int
objects. It is the maximum value of a Py_ssize_t
which is used (in CPython) for holding values of indexes.
For example, just create a larger int
than maxsize
:
>>> sys.getsizeof(sys.maxsize * sys.maxsize)
44
So, you get the number of bytes for a given int
by using getsizeof
on it.
*Bound, eventually, by available memory.
Upvotes: 2