考慮使用numpy的陣列,這是非常緩慢的下面的代碼:加速python中的一個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? –
我不需要完整的表現,我只是想加快速度。 – Vincent
從點tx,ty,tz構建一個'scipy.spatial.KDTree',然後在ox,oy,oz中的每個點的無限範圍內使用最近鄰居查找來查看是否有足夠接近的點。 –