【发布时间】:2014-01-03 01:27:00
【问题描述】:
我正在尝试想出一种更快的方式来编写我想要的代码。这是我正在尝试加速的程序部分,希望使用更多内置功能:
num = 0
num1 = 0
rand1 = rand_pos[0:10]
time1 = time.clock()
for rand in rand1:
for gal in gal_pos:
num1 = dist(gal, rand)
num = num + num1
time2 = time.clock()
time_elap = time2-time1
print time_elap
这里,rand_pos 和 gal_pos 分别是长度为 900 和 100 万的列表。 这里 dist 是计算欧几里得空间中两点之间距离的函数。 我使用了 rand_pos 的 sn-p 来进行时间测量。 我的时间测量值约为 125 秒。这也太长了吧! 这意味着如果我在所有 rand_pos 上运行代码,大约需要三个小时! 有没有更快的方法可以做到这一点?
这里是 dist 函数:
def dist(pos1,pos2):
n = 0
dist_x = pos1[0]-pos2[0]
dist_y = pos1[1]-pos2[1]
dist_z = pos1[2]-pos2[2]
if dist_x<radius and dist_y<radius and dist_z<radius:
positions = [pos1,pos2]
distance = scipy.spatial.distance.pdist(positions, metric = 'euclidean')
if distance<radius:
n = 1
return n
【问题讨论】:
-
可能,但发布实际代码,然后运行profiler 以查看导致瓶颈的原因。几乎可以肯定是你对
dist的实现应该受到责备。 -
我们看不到 dist,这可能很重要
-
我刚刚添加了 dist 函数@user3125280
-
我已经在使用 pdist @BrenBarn
标签: python performance function loops