我正在使用Cython的prange
来提高某些度量计算的性能。以下是我的代码:
def shausdorff(float64_t[:,::1] XA not None, float64_t[:,:,::1] XB not None):
cdef:
Py_ssize_t i
Py_ssize_t n = XB.shape[2]
float64_t[::1] hdist = np.zeros(n)
#arrangement to fix contiguity
XB = np.asanyarray([np.ascontiguousarray(XB[:,:,i]) for i in range(n)])
for i in range(n):
hdist[i] = _hausdorff(XA, XB[i])
return hdist
def phausdorff(float64_t[:,::1] XA not None, float64_t[:,:,::1] XB not None):
cdef:
Py_ssize_t i
Py_ssize_t n = XB.shape[2]
float64_t[::1] hdist = np.zeros(n)
#arrangement to fix contiguity (EDITED)
cdef float64_t[:,:,::1] XC = np.asanyarray([np.ascontiguousarray(XB[:,:,i]) for i in range(n)])
with nogil, parallel(num_threads=4):
for i in prange(n, schedule='static', chunksize=1):
hdist[i] = _hausdorff(XA, XC[i])
return hdist
基本上,每次迭代中都会在XA
和每个XB[i]
之间计算hausdorff度量。以下是_hausdorff
函数的签名:
cdef inline float64_t _hausdorff(float64_t[:,::1] XA, float64_t[:,::1] XB) nogil:
...
我的问题是顺序
shausdorff
和并行phausdorff
的时间相同。此外,似乎phausdorff
根本没有创建线程。那么我的问题是,我的代码有什么问题,我如何修复它以使线程工作。
这是我的
setup.py
:from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
ext_modules=[
Extension("custom_metric",
["custom_metric.pyx"],
libraries=["m"],
extra_compile_args = ["-O3", "-ffast-math", "-march=native", "-fopenmp" ],
extra_link_args=['-fopenmp']
)
]
setup(
name = "custom_metric",
cmdclass = {"build_ext": build_ext},
ext_modules = ext_modules
)
编辑1: 这里是由 cython -a
生成的html链接:custom_metric.html
编辑2: 这是一个调用相应函数的示例(您需要首先编译Cython文件)
import custom_metric as cm
import numpy as np
XA = np.random.random((9000, 210))
XB = np.random.random((1000, 210, 9))
#timing 'parallel' version
%timeit cm.phausdorff(XA, XB)
#timing sequential version
%timeit cm.shausdorff(XA, XB)
prange
循环体内打印等效于omp_get_thread_num()
的内容了吗?请参考http://cython.readthedocs.io/en/latest/src/userguide/parallelism.html。 - HaraldXB
是一个Python对象?使用注释运行cython -a custom_metric.pyx
。 - cgohlkeshausdorff
和phausdorff
的小例子吗? - Harald