【发布时间】:2020-06-15 01:51:59
【问题描述】:
我尝试使用 prange 来加速代码,但时间成本与初始版本几乎相同。初始版本如下:
%%cython -a --cplus
import cython
cdef extern from "<complex.h>" namespace "std" nogil:
double complex exp(double complex)
@cython.boundscheck(False)
@cython.wraparound(False)
def cphaseshift(double px,double py,double[:,:] kX,double[:,:] kY,double complex[:,:] f):
cdef double complex I = 1j
cdef double pi = 3.141592653589793
cdef int i
cdef int j
for i in range(kX.shape[0]):
for j in range(kY.shape[1]):
f[i,j] = f[i,j]*exp(-2*pi*I*(px*kX[i,j]+py*kY[i,j]))
初始版本的速度:
px = 1
py = 1
kx = np.linspace(1,256,256)
kX,kY = np.meshgrid(kx,kx)
f0 = np.ones_like(kX,dtype='complex128')
%timeit cphaseshift(px,py,kX,kY,f0)
2.07 ms ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
并行版本:
%%cython -a --cplus
import cython
from cython.parallel import prange
cdef extern from "<complex.h>" namespace "std" nogil:
double complex exp(double complex)
@cython.boundscheck(False)
@cython.wraparound(False)
def cphaseshift_para(double px,double py,double[:,:] kX,double[:,:] kY,double complex[:,:] f):
cdef double complex I = 1j
cdef double pi = 3.141592653589793
cdef int i
cdef int j
for i in prange(kX.shape[0],nogil=True,num_threads=6):
for j in range(kY.shape[1]):
f[i,j] = f[i,j]*exp(-2*pi*I*(px*kX[i,j]+py*kY[i,j]))
这个版本的速度:
px = 1
py = 1
kx = np.linspace(1,256,256)
kX,kY = np.meshgrid(kx,kx)
f0 = np.ones_like(kX,dtype='complex128')
%timeit cphaseshift_para(px,py,kX,kY,f0)
2.12 ms ± 28.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
我注意到for i in prange(kX.shape[0],nogil=True,num_threads=6): 暗示了 python 交互。如何正确使用并行来加速代码?谢谢!
【问题讨论】: