我想用各种性能说明来阐述简单的答案。 np.linalg.norm 可能会做的比你需要的更多:
dist = numpy.linalg.norm(a-b)
首先 - 此函数旨在处理列表并返回所有值,例如比较从pA 到点集sP 的距离:
sP = set(points)
pA = point
distances = np.linalg.norm(sP - pA, ord=2, axis=1.) # 'distances' is a list
记住几件事:
- Python 函数调用很昂贵。
- [常规] Python 不缓存名称查找。
所以
def distance(pointA, pointB):
dist = np.linalg.norm(pointA - pointB)
return dist
并不像看起来那么无辜。
>>> dis.dis(distance)
2 0 LOAD_GLOBAL 0 (np)
2 LOAD_ATTR 1 (linalg)
4 LOAD_ATTR 2 (norm)
6 LOAD_FAST 0 (pointA)
8 LOAD_FAST 1 (pointB)
10 BINARY_SUBTRACT
12 CALL_FUNCTION 1
14 STORE_FAST 2 (dist)
3 16 LOAD_FAST 2 (dist)
18 RETURN_VALUE
首先 - 每次我们调用它时,我们都必须对“np”进行全局查找,对“linalg”进行范围查找和对“norm”进行范围查找,以及仅调用的开销 em> 函数相当于几十条python指令。
最后,我们浪费了两个操作来存储结果并重新加载它以返回......
改进的第一步:加快查找速度,跳过存储
def distance(pointA, pointB, _norm=np.linalg.norm):
return _norm(pointA - pointB)
我们得到了更加精简:
>>> dis.dis(distance)
2 0 LOAD_FAST 2 (_norm)
2 LOAD_FAST 0 (pointA)
4 LOAD_FAST 1 (pointB)
6 BINARY_SUBTRACT
8 CALL_FUNCTION 1
10 RETURN_VALUE
不过,函数调用开销仍然需要一些工作。而且您需要进行基准测试以确定您自己是否可以更好地进行数学计算:
def distance(pointA, pointB):
return (
((pointA.x - pointB.x) ** 2) +
((pointA.y - pointB.y) ** 2) +
((pointA.z - pointB.z) ** 2)
) ** 0.5 # fast sqrt
在某些平台上,**0.5 比 math.sqrt 快。您的里程可能会有所不同。
**** 高级性能说明。
你为什么要计算距离?如果唯一的目的是展示它,
print("The target is %.2fm away" % (distance(a, b)))
继续前进。但是,如果您要比较距离、进行范围检查等,我想添加一些有用的性能观察。
让我们采取两种情况:按距离排序或从列表中剔除满足范围约束的项目。
# Ultra naive implementations. Hold onto your hat.
def sort_things_by_distance(origin, things):
return things.sort(key=lambda thing: distance(origin, thing))
def in_range(origin, range, things):
things_in_range = []
for thing in things:
if distance(origin, thing) <= range:
things_in_range.append(thing)
我们需要记住的第一件事是,我们使用Pythagoras 来计算距离(dist = sqrt(x^2 + y^2 + z^2)),因此我们进行了很多sqrt 调用。数学 101:
dist = root ( x^2 + y^2 + z^2 )
:.
dist^2 = x^2 + y^2 + z^2
and
sq(N) < sq(M) iff M > N
and
sq(N) > sq(M) iff N > M
and
sq(N) = sq(M) iff N == M
简而言之:在我们真正需要以 X 而不是 X^2 为单位的距离之前,我们可以消除计算中最困难的部分。
# Still naive, but much faster.
def distance_sq(left, right):
""" Returns the square of the distance between left and right. """
return (
((left.x - right.x) ** 2) +
((left.y - right.y) ** 2) +
((left.z - right.z) ** 2)
)
def sort_things_by_distance(origin, things):
return things.sort(key=lambda thing: distance_sq(origin, thing))
def in_range(origin, range, things):
things_in_range = []
# Remember that sqrt(N)**2 == N, so if we square
# range, we don't need to root the distances.
range_sq = range**2
for thing in things:
if distance_sq(origin, thing) <= range_sq:
things_in_range.append(thing)
太好了,这两个函数都不再做任何昂贵的平方根了。那会快很多。我们还可以通过将 in_range 转换为生成器来改进它:
def in_range(origin, range, things):
range_sq = range**2
yield from (thing for thing in things
if distance_sq(origin, thing) <= range_sq)
如果您正在执行以下操作,这尤其有好处:
if any(in_range(origin, max_dist, things)):
...
但如果你接下来要做的事情需要一段距离,
for nearby in in_range(origin, walking_distance, hotdog_stands):
print("%s %.2fm" % (nearby.name, distance(origin, nearby)))
考虑产生元组:
def in_range_with_dist_sq(origin, range, things):
range_sq = range**2
for thing in things:
dist_sq = distance_sq(origin, thing)
if dist_sq <= range_sq: yield (thing, dist_sq)
如果您可能会链接范围检查(“查找 X 附近和 Y 的 Nm 范围内的东西”,因为您不必再次计算距离),这将特别有用。
但是,如果我们正在搜索一个非常大的 things 列表并且我们预计其中有很多不值得考虑呢?
其实有一个很简单的优化:
def in_range_all_the_things(origin, range, things):
range_sq = range**2
for thing in things:
dist_sq = (origin.x - thing.x) ** 2
if dist_sq <= range_sq:
dist_sq += (origin.y - thing.y) ** 2
if dist_sq <= range_sq:
dist_sq += (origin.z - thing.z) ** 2
if dist_sq <= range_sq:
yield thing
这是否有用将取决于“事物”的大小。
def in_range_all_the_things(origin, range, things):
range_sq = range**2
if len(things) >= 4096:
for thing in things:
dist_sq = (origin.x - thing.x) ** 2
if dist_sq <= range_sq:
dist_sq += (origin.y - thing.y) ** 2
if dist_sq <= range_sq:
dist_sq += (origin.z - thing.z) ** 2
if dist_sq <= range_sq:
yield thing
elif len(things) > 32:
for things in things:
dist_sq = (origin.x - thing.x) ** 2
if dist_sq <= range_sq:
dist_sq += (origin.y - thing.y) ** 2 + (origin.z - thing.z) ** 2
if dist_sq <= range_sq:
yield thing
else:
... just calculate distance and range-check it ...
再一次,考虑让出 dist_sq。我们的热狗示例就变成了:
# Chaining generators
info = in_range_with_dist_sq(origin, walking_distance, hotdog_stands)
info = (stand, dist_sq**0.5 for stand, dist_sq in info)
for stand, dist in info:
print("%s %.2fm" % (stand, dist))