Python优化用于计算欧式距离

标签 python

此函数在我的程序中运行了超过 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

还有更多的performance tips on the python wiki.

关于Python优化用于计算欧式距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14994322/

相关文章:

python - 使用 Python/Selenium 选择单选按钮

python - POST 请求不适用于 token 验证检查

Python——输入 float 参数列表

python - 如何跟踪这个递归程序

python - 在python中将opencv图像写入zip文件

python - python可以抛出 "stack overflow"错误吗?

python - 如何使用 pandas 对行进行多重索引

python - 查找数据区间并对其进行排序

python - 没有空字符串的 Django CharField

python - 来自数组的直方图 matplotlib