我想使用 Cython 优化以下代码:
sim = numpy.dot(v1, v2) / (sqrt(numpy.dot(v1, v1)) * sqrt(numpy.dot(v2, v2)))
dist = 1-sim
return dist
我已经编写并编译了 .pyx 文件,当我运行代码时,我没有看到任何显着的性能改进。根据 Cython 文档,我必须添加 c_types。Cython 生成的 HTML 文件表明瓶颈是点积(这当然是意料之中的)。这是否意味着我必须为点积定义一个 C 函数?如果是,我该怎么做?
编辑:
经过一番研究,我想出了以下代码。改善只是微不足道的。我不确定是否可以做些什么来改进它:
from __future__ import division
import numpy as np
import math as m
cimport numpy as np
cimport cython
cdef extern from "math.h":
double c_sqrt "sqrt"(double)
ctypedef np.float reals #typedef_for easier readding
cdef inline double dot(np.ndarray[reals,ndim = 1] v1, np.ndarray[reals,ndim = 1] v2):
cdef double result = 0
cdef int i = 0
cdef int length = v1.size
cdef double el1 = 0
cdef double el2 = 0
for i in range(length):
el1 = v1[i]
el2 = v2[i]
result += el1*el2
return result
@cython.cdivision(True)
def distance(np.ndarray[reals,ndim = 1] ex1, np.ndarray[reals,ndim = 1] ex2):
cdef double dot12 = dot(ex1, ex2)
cdef double dot11 = dot(ex1, ex1)
cdef double dot22 = dot(ex2, ex2)
cdef double sim = dot12 / (c_sqrt(dot11 * dot22))
cdef double dist = 1-sim
return dist