【发布时间】:2020-09-03 11:14:21
【问题描述】:
我有模拟大量粒子之间相互作用的代码。使用分析,我发现导致最慢的函数是一个循环,它遍历我的所有粒子并计算出每个粒子之间的碰撞时间。这会生成一个对称矩阵,然后我会从中取出最小值。
def find_next_collision(self, print_matrix = False):
"""
Sets up a matrix of collision times
Returns the indices of the balls in self.list_of_balls that are due to
collide next and the time to the next collision
"""
self.coll_time_matrix = np.zeros((np.size(self.list_of_balls), np.size(self.list_of_balls)))
for i in range(np.size(self.list_of_balls)):
for j in range(i+1):
if (j==i):
self.coll_time_matrix[i][j] = np.inf
else:
self.coll_time_matrix[i][j] = self.list_of_balls[i].time_to_collision(self.list_of_balls[j])
matrix = self.coll_time_matrix + self.coll_time_matrix.T
self.coll_time_matrix = matrix
ind = np.unravel_index(np.argmin(self.coll_time_matrix, axis = None), self.coll_time_matrix.shape)
dt = self.coll_time_matrix[ind]
if (print_matrix):
print(self.coll_time_matrix)
return dt, ind
这段代码是一个类中的一个方法,它定义了所有粒子的位置。这些粒子中的每一个都是保存在self.list_of_balls(这是一个列表)中的一个对象。正如你所看到的,我已经只迭代了这个矩阵的一半,但它仍然是一个相当慢的函数。我试过使用 numba,但这是一段相当大的代码,我不想在速度慢的时候用 numba 优化每个函数。
有人对编写此函数的更有效方法有任何想法吗?
提前谢谢你!
【问题讨论】:
标签: python arrays loops numerical-computing