numpy.shares_memory#

numpy.shares_memory(a, b, /, max_work=None)#

确定两个数组是否共享内存.

警告

对于某些输入,此函数可能会呈指数级降低,除非将 max_work 设置为零或正整数. 如果有疑问,请改用 numpy.may_share_memory .

参数:
a, bndarray

输入数组

max_work整数,可选

花费在解决重叠问题上的精力(要考虑的最大候选解决方案数量). 识别以下特殊值:

max_work=-1(默认)

问题得到精确解决. 在这种情况下,仅当数组之间存在共享元素时,该函数才返回 True. 在某些情况下,找到精确的解决方案可能需要很长时间.

max_work=0

仅检查 a 和 b 的内存范围. 这等效于使用 may_share_memory() .

返回:
outbool
提出:
numpy.exceptions.TooHardError

超过 max_work.

示例

>>> import numpy as np
>>> x = np.array([1, 2, 3, 4])
>>> np.shares_memory(x, np.array([5, 6, 7]))
False
>>> np.shares_memory(x[::2], x)
True
>>> np.shares_memory(x[::2], x[1::2])
False

检查两个数组是否共享内存是 NP 完全问题,并且运行时间可能会随着维度的增加而呈指数增长. 因此,通常应将 max_work 设置为有限的数值,因为可以构建需要极长时间才能运行的示例:

>>> from numpy.lib.stride_tricks import as_strided
>>> x = np.zeros([192163377], dtype=np.int8)
>>> x1 = as_strided(
...     x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049))
>>> x2 = as_strided(
...     x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1))
>>> np.shares_memory(x1, x2, max_work=1000)
Traceback (most recent call last):
...
numpy.exceptions.TooHardError: Exceeded max_work

在此示例中,在未设置 max_work 的情况下运行 np.shares_memory(x1, x2) 大约需要 1 分钟. 可以找到运行时间更长的问题.