无论如何,我可以知道python中特定变量占用的字节数。例如;让我说我有
int = 12
print (type(int))
它会打印
<class 'int'>
但是我想知道它在内存上占用了多少字节?有可能吗?
答案 0 :(得分:34)
您可以找到所需的功能here(在sys.getsizeof
- Python 2.6及更高版本中)。
另外:不要遮蔽int
内置的!
import sys
myint = 12
print sys.getsizeof(myint)
答案 1 :(得分:9)
如果你想知道int的大小,你可以使用struct
>>> import struct
>>> struct.calcsize("i")
4
否则,正如其他人已经指出的那样,使用getsizeof(2.6)。你可以试试recipe。
答案 2 :(得分:5)
在Python&gt; = 2.6中,您可以使用sys.getsizeof。
答案 3 :(得分:2)
答案 4 :(得分:2)
在python命令提示符下,您可以使用函数的大小
$ import python
$ import ctypes
$ ctypes.sizeof(ctypes.c_int)
了解更多内容
答案 5 :(得分:2)
Numpy提供基础设施来控制数据大小。以下是示例(py3):
import numpy as np
x = np.float32(0)
print(x.nbytes) # 4
a = np.zeros((15, 15), np.int64)
print(a.nbytes) # 15 * 15 * 8 = 1800
例如,当尝试使用pyopengl向图形卡提交数据时,这非常有用。
答案 6 :(得分:0)
在Python 3中,您可以使用sys.getsizeof()。
import sys
myint = 12
print(sys.getsizeof(myint))
答案 7 :(得分:0)
最好的库是guppy:
import guppy
import inspect
def get_object_size(obj):
h = guppy.hpy()
callers_local_vars = inspect.currentframe().f_back.f_locals.items()
vname = "Constant"
for var_name, var_val in callers_local_vars:
if var_val == obj:
vname = str(var_name)
size = str("{0:.2f} GB".format(float(h.iso(obj).domisize) / (1024 * 1024)))
return str("{}: {}".format(vname, size))