一个2d numpy数组元素被提升到另一个2d数组的幂



我需要将一个大的2d numpy数组元素提高到另一个具有相同维度的2d数组的幂。我试着用麻木来提高速度。是否有使用numpy内置函数而不是numba的有效实现?

import numpy as np
from time import time

def elewise_power_raw(x, y):
z = np.zeros((n, n))
for i in range(n):
for j in range(n):
z[i,j] = x[i,j]**y[i,j]
return z

import numba
@numba.njit
def elewise_power_numba(x, y):
n = x.shape[0]
z = np.zeros((n, n))
for i in range(n):
for j in range(n):
z[i,j] = x[i,j]**y[i,j]
return z

def measure_time(n=5000):
x = np.random.rand(n, n)
y = np.random.rand(n, n)
t0 = time()
elewise_power_raw(x, y)
print('Raw: ', round(time() - t0, 2), 's' )
t1 = time()
elewise_power_numba(x, y)
print('numba: ', round(time() - t1, 2), 's' )

measure_time(5000)
# Raw:  22.31 s
# numba:  1.4 s

您可以随时对其进行矢量化。

x = np.random.rand(5000, 5000)
y = np.random.rand(5000, 5000)
%timeit x**y
977 ms ± 7.01 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

相关内容

  • 没有找到相关文章

最新更新