此函数在我的程序中运行了超过 200 万次。谁能建议优化这个? x 和 y 是元组。
def distance(x,y):
return sqrt((x[0]-y[0])*(x[0]-y[0])+(x[1]-y[1])*(x[1]-y[1])+(x[2]-y[2])*(x[2]-y[2]))
我的尝试:我尝试使用 math.sqrt、pow 和 x**.5,但没有太大的性能提升。
最佳答案
您可以通过不访问相同的 x[i] 元素并在本地绑定(bind)它来减少一些周期。
def distance(x,y):
x0, x1, x2 = x
y0, y1, y2 = y
return sqrt((x0-y0)*(x0-y0)+(x1-y1)*(x1-y1)+(x2-y2)*(x2-y2))
例子,比较:
>>> import timeit
>>> timer = timeit.Timer(setup='''
... from math import sqrt
... def distance(x,y):
... return sqrt((x[0]-y[0])*(x[0]-y[0])+(x[1]-y[1])*(x[1]-y[1])+(x[2]-y[2])*(x[2]-y[2]))
... ''', stmt='distance((0,0,0), (1,2,3))')
>>> timer.timeit(1000000)
1.2761809825897217
与:
>>> import timeit
>>> timer = timeit.Timer(setup='''
... from math import sqrt
... def distance(x,y):
... x0, x1, x2 = x
... y0, y1, y2 = y
... return sqrt((x0-y0)*(x0-y0)+(x1-y1)*(x1-y1)+(x2-y2)*(x2-y2))
... ''', stmt='distance((0,0,0), (1,2,3))')
>>> timer.timeit(1000000)
0.8375771045684814
关于Python优化用于计算欧式距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14994322/