在python中加速numpy循环?

Vin*_*ent 6 python iteration optimization loops numpy

考虑使用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
Run Code Online (Sandbox Code Playgroud)

如何重写函数来加速计算?(np.size(tx) == 10000np.size(ox) == 100000)

Ole*_*yar 6

您正在分配10000个大小为100000的列表.首先要做的是停止使用range嵌套j循环并使用生成器版本xrange.这将节省您分配所有这些列表的时间和空间.

下一个是使用矢量化操作:

for i in xrange(0, np.size(tx)):
    index = (ox-oe < tx[i]) & (ox+oe > tx[i]) & (oy-oe < ty[i]) & (oy+oe > ty[i]) & (oz-oe < tz[i]) & (oz+oe > tz[i])
    result[index] += 1  
Run Code Online (Sandbox Code Playgroud)