您无法在 numpy 数组上应用 log 等 C 函数,并且 numpy 没有可以从 cython 调用的 C 函数库。
Numpy 函数已经经过优化,可以在 numpy 数组上调用。除非您有非常独特的用例,否则您不会从将 numpy 函数重新实现为 C 函数中获得太多好处。 (numpy 中的某些函数可能没有很好地实现,在这种情况下请考虑将您的输入作为补丁提交。)但是您确实提出了一个很好的观点。
# A
from libc.math cimport log
for i in range(N):
r[i] = log(foo[i])
# B
r = np.log(foo)
# C
for i in range(n):
r[i] = np.log(foo[i])
一般来说,A 和 B 应该有相似的运行时间,但 C 应该避免,并且会慢很多。
Update
这是 scipy.stats.norm.pdf 的代码,您可以看到它是用 python 编写的,带有 numpy 和 scipy 调用。该代码没有 C 版本,您必须“通过 python”调用它。如果这是阻碍您的原因,您需要将其重新植入 C/Cython 中,但首先我会花一些时间非常仔细地分析代码,看看是否有任何容易实现的目标。
def pdf(self,x,*args,**kwds):
loc,scale=map(kwds.get,['loc','scale'])
args, loc, scale = self._fix_loc_scale(args, loc, scale)
x,loc,scale = map(asarray,(x,loc,scale))
args = tuple(map(asarray,args))
x = asarray((x-loc)*1.0/scale)
cond0 = self._argcheck(*args) & (scale > 0)
cond1 = (scale > 0) & (x >= self.a) & (x <= self.b)
cond = cond0 & cond1
output = zeros(shape(cond),'d')
putmask(output,(1-cond0)+np.isnan(x),self.badvalue)
if any(cond):
goodargs = argsreduce(cond, *((x,)+args+(scale,)))
scale, goodargs = goodargs[-1], goodargs[:-1]
place(output,cond,self._pdf(*goodargs) / scale)
if output.ndim == 0:
return output[()]
return output