我有一个简单的循环,仅对 numpy 数组的第二行求和。在 numba 我只需要做:
\nfrom numba import njit\n@njit(\'float64(float64[:, ::1])\', fastmath=True)\n def fast_sum_nb(array_2d):\n s = 0.0\n for i in range(array_2d.shape[1]):\n s += array_2d[1, i]\n return s\nRun Code Online (Sandbox Code Playgroud)\n如果我对代码进行计时,我会得到:
\nIn [3]: import numpy as np\nIn [4]: A = np.random.rand(2, 1000)\nIn [5]: %timeit fast_sum_nb(A)\n305 ns \xc2\xb1 7.81 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1,000,000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n要在 cython 中执行相同的操作,我需要首先 make setup.py ,其中包含:
\nfrom setuptools import setup\nfrom Cython.Build import cythonize\nfrom setuptools.extension import Extension\n\next_modules = [\n …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Cython 中循环 2 个 2d 数组。数组具有以下形状:
ranges_1是 的 6000x3 数组int64,而ranges_2是 的 2000x2 数组int64。这个迭代需要执行10000次左右。这意味着嵌套 for 循环内的计算总数约为 2000x6000x10000 = 1200 亿次。
这是我用来生成“虚拟”数据的代码:
import numpy as np
ranges_1 = np.stack([np.random.randint(0, 10_000, 6_000), np.random.randint(0, 10_000, 6_000), np.arange(0, 6_000)], axis=1)
ranges_2 = np.stack([np.random.randint(0, 10_000, 2_000), np.random.randint(0, 10_000, 2_000)], axis=1)
Run Code Online (Sandbox Code Playgroud)
这给出了 2 个像这样的数组:
array([[6131, 1478, 0],
[9317, 7263, 1],
[7938, 6249, 2],
...,
[5153, 426, 5997],
[9164, 9211, 5998],
[1695, 1792, 5999]])
Run Code Online (Sandbox Code Playgroud)
和:
array([[ 433, 558],
[3420, 2494], …Run Code Online (Sandbox Code Playgroud)