NumPy阵列内存管理 [英] Numpy array memory management
问题描述
我对Numpy阵列内存管理有疑问.假设我使用以下命令从缓冲区创建一个numpy数组:
I have a question about Numpy array memory management. Suppose I create a numpy array from a buffer using the following:
>>> s = "abcd"
>>> arr = numpy.frombuffer(buffer(s), dtype = numpy.uint8)
>>> arr.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : False
ALIGNED : True
UPDATEIFCOPY : False
>>> del s # What happens to arr?
在上述情况下,"arr"是否引用了"s"?如果我删除"s",这会释放为"s"分配的内存,从而使"arr"潜在地引用未分配的内存吗?
In the situation above, does 'arr' hold a reference to 's'? If I delete 's', will this free the memory allocated for 's' and thus make 'arr' potentially referencing unallocated memory?
我还有其他一些问题:
- 如果这是有效的,Python如何知道何时释放由s分配的内存? gc.get_referrents(arr)函数似乎并不表明'arr'持有对's'的引用.
- 如果这是无效的,我如何将对"s"的引用注册到"arr"中,以便当所有对它的引用都消失时,Python GC会自动获得"s"?
推荐答案
以下内容应使事情澄清一些:
The following should clarify things a little:
>>> s = 'abcd'
>>> arr = np.frombuffer(buffer(s), dtype='uint8')
>>> arr.base
<read-only buffer for 0x03D1BA60, size -1, offset 0 at 0x03D1BA00>
>>> del s
>>> arr.base
<read-only buffer for 0x03D1BA60, size -1, offset 0 at 0x03D1BA00>
在第一种情况下,del s
不起作用,因为数组指向的是从中创建的buffer
,在其他任何地方均未引用该数组.
In the first case del s
has no effect, because what the array is pointing to is a buffer
created from it, which is not referenced anywhere else.
>>> t = buffer('abcd')
>>> arr = np.frombuffer(t, dtype='uint8')
>>> arr.base
<read-only buffer for 0x03D1BA60, size -1, offset 0 at 0x03C8D920>
>>> arr.base is t
True
>>> del t
>>> arr.base
<read-only buffer for 0x03D1BA60, size -1, offset 0 at 0x03C8D920>
在第二种情况下,当您使用del t
时,您摆脱了指向buffer
对象的变量t
,但是由于数组仍然具有对该同一buffer
的引用,因此不会将其删除.虽然我不确定如何检查它,但是如果您现在del arr
,则buffer
对象应该丢失其最后一个引用,并会自动进行垃圾收集.
In the second case, when you del t
, you get rid of the variable t
pointing to the buffer
object, but because the array still has a reference to that same buffer
, it is not deleted. While I am not sure how to check it, if you now del arr
, the buffer
object should lose its last reference and be automatically garbage-collected.
这篇关于NumPy阵列内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!