numpy.shares_memory和numpy.may_share_memory有什么区别?

numpy.shares_memory和numpy.may_share_memory有什么区别?,第1张

numpy.shares_memory和numpy.may_share_memory有什么区别?

引用1.11.0的发行说明:

添加了一个新功能

np.shares_memory
,该功能可以准确检查两个数组是否存在内存重叠。
np.may_share_memory
现在还可以选择花更多的精力来减少误报。

从语义上讲,这表明较早的

may_share_memory
测试旨在让您轻松地猜测是否在阵列之间共享内存。如果肯定没有,那么可以相应地进行。如果存在阳性测试(可能是假阳性),则必须小心。
shares_memory
另一方面,新功能允许进行精确检查。这会花费更多的计算时间,但从长远来看可能是有益的,因为可以避免误报,可以使用更多可能的优化方法。更宽松的检查
may_share_memory
可能仅保证不返回假
阴性

在文档方面

may_share_memory
shares_memory
,都有告诉numpy的严格一件多么检查用户想要一个关键字参数。

may_share_memory

max_work : int, optional    Effort to spend on solving the overlap problem. See shares_memory for details. Default for may_share_memory is to do a bounds check.

shares_memory

max_work : int, optional    Effort to spend on solving the overlap problem (maximum number of candidate solutions to consider). The following special values are recognized:    max_work=MAY_SHARE_EXACT (default)        The problem is solved exactly. In this case, the function returns True only if there is an element shared between the arrays.    max_work=MAY_SHARE_BOUNDS        only the memory bounds of a and b are checked.

根据文档判断,这表明这两个函数可能调用相同的基础机制,但是

may_share_memory
对检查使用了不太严格的默认设置。

让我们看一下实现:

static PyObject *array_shares_memory(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds){    return array_shares_memory_impl(args, kwds, NPY_MAY_SHARE_EXACT, 1);}static PyObject *array_may_share_memory(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *kwds){    return array_shares_memory_impl(args, kwds, NPY_MAY_SHARE_BOUNDS, 0);}

用签名调用相同的基础函数

static PyObject *array_shares_memory_impl(PyObject *args, PyObject *kwds, Py_ssize_t default_max_work,   int raise_exceptions){}

在不深入研究源代码的情况下,在我看来,它

shares_memory
是对的改进
may_share_memory
,可以使用适当的关键字参数对后者进行同样的宽松检查。较旧的功能可用于方便和向后兼容。

免责声明:这是我第一次查看源代码的这一部分,并且没有进一步研究

array_shares_memory_impl
,因此我的印象可能是错误的。


关于这两种方法之间的区别的特定示例(使用默认参数调用):在以上链接中进行了解释,该链接

may_share_memory
仅检查数组绑定索引。如果它们是不相交的两个数组,然后有
没有机会 ,他们可以共享内存。但是,如果它们 不是 不相交的,则数组仍可以是独立的!

一个简单的例子:通过切片对内存的连续块进行不相交的分区:

>>> import numpy as np>>> v = np.arange(6)>>> x = v[::2]>>> y = v[1::2]>>> np.may_share_memory(x,y)True>>> np.shares_memory(x,y)False>>> np.may_share_memory(x,y,max_work=np.MAY_SHARE_EXACT)False

如您所见,

x
并且
y
是同一数组的两个不相交的切片。因此,它们的数据范围在很大程度上重叠(它们几乎相同,在内存中保存单个整数)。但是,它们的元素实际上并不相同:一个包含原始连续块的偶数元素,另一个包含奇数元素。因此可以
may_share_memory
正确地断言数组
可以 共享内存,但是经过严格的检查,结果发现它们不共享内存。


至于精确计算重叠的额外困难,可以将工作追溯到名为的工作人员

solve_may_share_memory
,该工作人员还包含许多有关正在发生的事情的有用评论。简而言之,

  1. a quick check and return
    如果边界 重叠,否则
  2. 一个有回报
    MEM_OVERLAP_TOO_HARD
    ,如果我们要求宽松检查(即
    may_share_memory
    使用默认参数),这是在调用侧的处理是“我们不知道,这样的回报
    True
  3. 否则,我们实际上会解决问题映射到此处的Diophantine方程

因此,以上第3点中的工作是需要额外完成的

shares_memory
(或者通常是严格检查的情况)。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5649102.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存