我需要检查一个点是否在一个边界立方体内。需要检查的立方体数量非常大(约为4M)。我编写的代码如下:
import numpy as np
# set the numbers of points and cuboids
n_points = 64
n_cuboid = 4000000
# generate the test data
points = np.random.rand(1, 3, n_points)*512
cuboid_min = np.random.rand(n_cuboid, 3, 1)*512
cuboid_max = cuboid_min + np.random.rand(n_cuboid, 3, 1)*8
# main body: check if the points are inside the cuboids
inside_cuboid = np.all((points > cuboid_min) & (points < cuboid_max), axis=1)
indices = np.nonzero(inside_cuboid)
在我的电脑上,运行np.all
需要8秒钟,而运行np.nonzero
只需要3秒钟。有什么方法可以加速代码吗?