numpy.shares_memory#
- numpy.shares_memory(a, b, /, max_work=None)#
判斷兩個陣列是否共用記憶體。
警告
對於某些輸入,此函數可能會呈指數級地慢,除非將 max_work 設定為零或正整數。如有疑問,請改用
numpy.may_share_memory
。- 參數:
- a, bndarray
輸入陣列
- max_workint,選用
用於解決重疊問題的努力程度(要考慮的最大候選解決方案數量)。以下特殊值被識別
- 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 分鐘。有可能找到需要更長時間才能解決的問題。