作为一般的经验法则,尽可能坚持 scipy 和 numpy 实现,因为它们被矢量化并且比本机Python代码快得多 . (主要原因是:在C中实现,向量化消除了循环所做的类型检查开销 . )
(旁白:我的答案不包括这里的精度,但我认为同样的原则适用于效率的精确度 . )
作为一个奖励,我重新使用IPython解释器,秘诀是使用 %prun 线魔术 .
In [1]: import numpy
In [2]: from scipy.spatial import distance
In [3]: c1 = numpy.array((52, 106, 35, 12))
In [4]: c2 = numpy.array((33, 153, 75, 10))
In [5]: %prun distance.euclidean(c1, c2)
35 function calls in 0.000 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 linalg.py:1976(norm)
1 0.000 0.000 0.000 0.000 {built-in method numpy.core.multiarray.dot}
6 0.000 0.000 0.000 0.000 {built-in method numpy.core.multiarray.array}
4 0.000 0.000 0.000 0.00