Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i determine the exact size of a type used by python

Tags:

python

>>> sys.getsizeof(int)
436 #? does this mean int occupies 436 bytes .

>>> sys.getsizeof(1)
12 #12 bytes for int object, is this the memory requirement.

I thought int in python is represented by 4 bytes, why is it reporting 12 bytes

Please someone explain why is it reporting 12 bytes when int uses just 4 bytes

like image 629
George Avatar asked Oct 15 '11 16:10

George


People also ask

What is __ sizeof __ in Python?

The Python __sizeof__() method returns the size of the object in bytes. The sys. getsizeof() method internally call's __sizeof__() and adds some additional byte overhead, e.g., for garbage collection.

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 find the int size in Python?

To get the length of an integer in Python:Use the str() class to convert the integer to a string, e.g. result = str(my_int) . Pass the string to the len() function, e.g. len(my_str) . The len() function will return the length of the string.

How do you find the size of an object?

One way to get an estimate of an object's size in Java is to use getObjectSize(Object) method of the Instrumentation interface introduced in Java 5. As we could see in Javadoc documentation, the method provides “implementation-specific approximation” of the specified object's size.


1 Answers

Yes, an int instance takes up 12 bytes on your system. Integers (like any object) have attributes, i.e. pointers to other objects, which take up additional memory space beyond that used by the object's own value. So 4 bytes for the integer's value, 4 bytes for a pointer to __class__ (otherwise, Python wouldn't know what type the object belonged to and how to start resolving attribute names that are inherited from the int class and its parents), and another 4 for the object's reference count, which is used by the garbage collector.

The type int occupies 436 bytes on your system, which will be pointers to the various methods and other attributes of the int class and whatever other housekeeping information Python requires for the class. The int class is written in C in the standard Python implementation; you could go look at the source code and see what's in there.

like image 54
kindall Avatar answered Nov 14 '22 22:11

kindall