为什么int需要三倍于Python的内存? [英] Why do ints require three times as much memory in Python?
问题描述
在64位系统上,Python中的整数需要24个字节。这是例如所需内存的3倍。 C表示64位整数。现在,我知道这是因为Python整数是对象。但是用于的额外内存是多少?我有我的猜测,但肯定知道这将是很好的。
On a 64-bit system an integer in Python takes 24 bytes. This is 3 times the memory that would be needed in e.g. C for a 64-bit integer. Now, I know this is because Python integers are objects. But what is the extra memory used for? I have my guesses, but it would be nice to know for sure.
推荐答案
请记住Python int
类型没有有限的范围,如C int
has;唯一的限制是可用内存。
Remember that the Python int
type does not have a limited range like C int
has; the only limit is the available memory.
内存用于存储值,整数存储的当前大小(存储大小可变,以支持任意大小),以及标准的Python对象簿记(对相关对象的引用和引用计数)。
Memory goes to storing the value, the current size of the integer storage (the storage size is variable to support arbitrary sizes), and the standard Python object bookkeeping (a reference to the relevant object and a reference count).
你可以查找 longintrepr.h
source (Python 3 int
类型在Python 2中传统上称为 long
类型;它有效地利用了 PyVarObject
C类型跟踪整数大小:
You can look up the longintrepr.h
source (the Python 3 int
type was traditionally known as the long
type in Python 2); it makes effective use of the PyVarObject
C type to track integer size:
struct _longobject {
PyObject_VAR_HEAD
digit ob_digit[1];
};
ob_digit
数组存储数字 15或30位宽(取决于您的平台);所以在我的64位OS X系统上,一个最大为(2 ^ 30)的整数 - 1使用1'数字':
The ob_digit
array stores 'digits' of either 15 or 30 bits wide (depending on your platform); so on my 64-bit OS X system, an integer up to (2 ^ 30) - 1 uses 1 'digit':
>>> sys.getsizeof((1 << 30) - 1)
28
但是如果您在数字中使用2个30位数字,则需要额外的4个字节,等等:
but if you use 2 30-bit digits in the number an additional 4 bytes are needed, etc:
>>> sys.getsizeof(1 << 30)
32
>>> sys.getsizeof(1 << 60)
36
>>> sys.getsizeof(1 << 90)
40
基数24字节然后是 PyObject_VAR_HEAD
结构,包含对象大小,引用计数和类型指针(在我的64位OS X平台上每8字节/ 64位)。
The base 24 bytes then are the PyObject_VAR_HEAD
structure, holding the object size, the reference count and the type pointer (each 8 bytes / 64 bits on my 64-bit OS X platform).
在Python 2上,整数< = sys.maxint
但是> = -sys.maxint - 使用更简单的结构存储1
单个值:
On Python 2, integers <= sys.maxint
but >= -sys.maxint - 1
are stored using a simpler structure storing just the single value:
typedef struct {
PyObject_HEAD
long ob_ival;
} PyIntObject;
因为它使用 PyObject
而不是 PyVarObject
结构中没有 ob_size
字段,内存大小仅限于24个字节; 8为 long
值,8为引用计数,8为类型对象指针。
because this uses PyObject
instead of PyVarObject
there is no ob_size
field in the struct and the memory size is limited to just 24 bytes; 8 for the long
value, 8 for the reference count and 8 for the type object pointer.
这篇关于为什么int需要三倍于Python的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!