【发布时间】:2014-07-27 02:46:56
【问题描述】:
考虑以下使用非常慢的 numpy 数组的代码:
# Intersection of an octree and a trajectory
def intersection(octree, trajectory):
# Initialize numpy arrays
ox = octree.get("x")
oy = octree.get("y")
oz = octree.get("z")
oe = octree.get("extent")/2
tx = trajectory.get("x")
ty = trajectory.get("y")
tz = trajectory.get("z")
result = np.zeros(np.size(ox))
# Loop over elements
for i in range(0, np.size(tx)):
for j in range(0, np.size(ox)):
if (tx[i] > ox[j]-oe[j] and
tx[i] < ox[j]+oe[j] and
ty[i] > oy[j]-oe[j] and
ty[i] < oy[j]+oe[j] and
tz[i] > oz[j]-oe[j] and
tz[i] < oz[j]+oe[j]):
result[j] += 1
# Finalize
return result
如何重写函数以加快计算速度? (np.size(tx) == 10000 和np.size(ox) == 100000)
【问题讨论】:
-
您是否也考虑使用 OpenCL?
-
我不需要完整的性能,我只想要原始速度。
-
从点 tx, ty, tz 构建一个
scipy.spatial.KDTree然后对 ox, oy, oz 中的每个点使用无穷范数中的最近邻查找来查看是否有任何点足够接近。 -
你考虑过使用 Cython 吗?我读过它可以在没有太多痛苦的情况下提供很大的加速。 stackoverflow.com/questions/7799977/numpy-vs-cython-speed
标签: python loops optimization numpy iteration