【发布时间】:2021-12-31 10:07:09
【问题描述】:
我最近看到,当通过np.empty 或np.zeros 创建一个numpy 数组时,该numpy 数组的内存实际上并没有像this answer(和this question)中讨论的那样由操作系统分配,因为numpy利用calloc 分配数组的内存。
实际上,在您尝试访问之前,操作系统甚至不会“真正”分配该内存。
因此,
l = np.zeros(2**28)
不会增加系统报告的已用内存,例如htop。
只有一次我触摸内存,例如通过执行
np.add(l, 0, out=l)
使用的内存增加了。
由于这种行为,我有几个问题:
1。被感动的记忆是在幕后复制的吗?
如果我只是在一段时间后才触摸内存块,操作系统是否会在后台复制 numpy 数组的内容以保证内存是连续的?
i = 100
f[:i] = 3
while True:
... # Do stuff
f[i] = ... # Once the memory "behind" the already allocated chunk of memory is filled
# with other stuff, does the operating system reallocate the memory and
# copy the already filled part of the array to the new location?
i = i + 1
2。触摸最后一个元素
由于numpy数组的内存在内存中是连续的,所以我坚持
f[-1] = 3
可能需要分配整个内存块(不涉及整个内存)。 但是,事实并非如此,htop 中使用的内存不会随着数组的大小而增加。 为什么不是这样?
【问题讨论】:
-
这是一个实现细节,你作为 python 级别的编码器无法操作。
标签: python python-3.x numpy memory calloc