Python中变量的内存大小 [英] Variable's memory size in Python
问题描述
我正在编写Python代码来进行一些大数计算,并且非常担心计算中使用的内存.
I am writing Python code to do some big number calculation, and have serious concern about the memory used in the calculation.
因此,我想计算每个变量的每一位.
Thus, I want to count every bit of each variable.
例如,我有一个变量 x ,它是一个很大的数字,并且想要计算表示 x 的位数.
For example, I have a variable x, which is a big number, and want to count the number of bits for representing x.
以下代码显然是无用的:
The following code is obviously useless:
x=2**1000
len(x)
因此,我转向使用以下代码:
Thus, I turn to use the following code:
x=2**1000
len(repr(x))
变量 x 为(十进制)为:
1071508607186267320948425049069068108105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062362371141877954182153043044984983581941267398767559165543946077062914571696477686476867678965
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
但是上面的代码返回 303
上面的long long序列的长度为302,因此我认为 303 应该仅与字符串长度有关.
The above long long sequence is of length 302, and so I believe that 303 should be related to the string length only.
所以,这是我最初的问题:
So, here comes my original question:
我怎么知道变量 x 的内存大小?
How can I know the memory size of variable x?
还有一件事情;如果我定义的话,使用C/C ++语言
One more thing; in C/C++ language, if I define
int z=1;
这意味着为 z 分配了4个字节= 32位,并且这些位安排为00..001(31个0和一个1).
This means that there are 4 bytes= 32 bits allocated for z, and the bits are arranged as 00..001(31 0's and one 1).
在这里,我的变量 x 很大,我不知道它是否遵循相同的内存分配规则?
Here, my variable x is huge, I don't know whether it follows the same memory allocation rule?
推荐答案
使用 sys.getsizeof
获取对象的大小(以字节为单位).
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
>>>
请注意,对象的大小和布局纯粹是特定于实现的.例如,CPython可能使用与IronPython完全不同的内部数据结构.因此,对象的大小可能因实现而异.
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.
这篇关于Python中变量的内存大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!