Fai*_*rbw -1 python optimization loops
我的问题很简单.我有一个像这样的python简单代码:
for i in range(1,1193616,1) :
print i
Run Code Online (Sandbox Code Playgroud)
因此,将打印范围1中的所有数字,直到1193616,这个循环进度需要很长时间..如何使其快速?
编辑:
实际上,我尝试为图像数据(Raster)制作一个A-star寻路程序.到目前为止,这是我的A-star函数脚本:
def A_star(h,c,dx,dy,u,s_id,e_id,Op,Cl,Prt,CC,o,ht,w):
Op.append(s_id)
while e_id not in Op :
if Op == [ ] :
break
candidate = { }
for i in Op :
d = {i : CC[i]}
candidate.update(d)
o = min(candidate, key=candidate.get)
Cl.append(o)
Op.remove(o)
adjacent_list = adjacent_cell(o,dx,dy )
for p in adjacent_list :
if p in Cl:
adjacent_list = filter(lambda i: i != p, adjacent_list)
elif p not in Op :
Op.append(p)
d = {p : o }
Prt.update(d)
d = {p : F(p,o,h,u,w,c,dx,e_id,ht,CC)}
CC.update(d)
elif id in Op :
f1 = F(p,o,h,u,w,c,dx,e_id,ht,CC)
f2 = F(p,Prt[p],h,u,w,c,dx,e_id,ht,CC)
if f1 < f2 :
d = {p : o }
Prt.update(d)
d = {id : F(p,o,h,u,w,c,dx,e_id,ht,CC)}
CC.update(d)
return Prt
Run Code Online (Sandbox Code Playgroud)
假设s_id = 1(开始)和e_id = 1193616(结束),第3行发生了长时间循环进度
while e_id not in Op :
有没有办法加速或优化我的代码?
通常缓慢的是输出,而不是循环; 你可以这样做:
print '\n'.join('%s' % c for c in range(1, 1193616))
Run Code Online (Sandbox Code Playgroud)
编辑:
在我的系统上,当输出是一个终端时,你的代码需要10.193s,我的版本需要2.374s.如果它被重定向到一个文件,它是0.486s vs 0.572s(差别不大).
请注意,在一次写入之前将所有数据"缓冲"到程序中并不总是最好的解决方案(可能耗尽内存资源),我怀疑打印到超过数百行的终端是有用的. ..