numpy.shares_memory#

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

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

警告

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

参数:
a, bndarray

输入数组

max_workint, optional

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

max_work=-1(默认)

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

max_work=0

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

返回:
outbool
Raises:
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_worknp.shares_memory(x1, x2) 大约需要 1 分钟.可以找到运行时间更长的问题.