加速python 3.5循环以像python一样快速运行它

Los*_*ica 2 python performance cython python-3.x

我需要计算海量数据中2 xyz点之间的距离(100 Gb,大约20个trylion点).我想加快这个循环.我创建了KDtree,添加了并行计算,将我的数组拆分为更小的部分.所以我想加速的就是这个循环.我的纯python计算时间大约需要10小时42分钟.增加numpy减少时间为5小时34分钟.添加numba速度可达4小时15分钟.但它仍然不够快.我听说Cython是python计算的最快方式,但我没有任何c经验,我不知道如何将我的函数转换为cython代码.如何使用cython或任何其他方式让这个循环更快地运行?

def controller(point_array, las_point_array):  

    empty = []


    tree = spatial.cKDTree(point_array, leafsize=1000, copy_data = True)   

    empty = __pure_calc(las_point_array, point_array, empty, tree)  

    return ptList   

#############################################################################################

@autojit
def __pure_calc(las_point_array, point_array, empty, tree):

    for i in las_point_array:
            p = tree.query(i)   

            euc_dist = math.sqrt(np.sum((point_array[p[1]]-i)**2))  

            ##add one row at a time to empty list
            empty.append([i[0], i[1], i[2], euc_dist, point_array[p[1]][0], point_array[p[1]][1], point_array[p[1]][2]]) 

    return empty
Run Code Online (Sandbox Code Playgroud)

我附上样本数据进行测试:

样品

Joh*_*nck 5

你的函数构建一个list(closestPt),最终看起来像这样:

[
    [i0[0], i0[1], i0[2], distM0],
    [i1[0], i1[1], i1[2], distM1],
    ...
]
Run Code Online (Sandbox Code Playgroud)

您应该做的第一件事是将整个结果预先分配为NumPy数组(np.empty()),并一次写入一行.这将避免大量的内存分配.然后你会注意到你可以推迟sqrt()到最后,并distM在你的循环完成后在列上运行它.

如果您使用随机/样本输入数据发布完整的工作测试工具,则可能会有更多优化机会.