在Python中及时停止循环。

时间:2013-11-07 11:04:08

标签: python

我的代码中有五个循环,我希望在设置时停止每个循环。我的代码是:

nw=1000
for i in range(nw):
    w_list.append(-3+0.006*i)
    chi_1=0
    chi_2=0
    k=1
    while k<10:
            now_1=time.time()
            l=1
            while l<10:
                    now_2=time.time()
                    n_1=0
                    while n_1<10:
                            now_3=time.time()
                            n_2=0
                            while n_2<5:
                                    now_4=time.time()
                                    chi_2+=(e1_vecs[n_1,0]*e1_vecs[n_1,k]*e_vecs[2*n_2,0]*e_vecs[2*n_2,l])**2*(1.0/(w_list[i]+(E0-e_vals[l]-k*w_b+b*w_b)-0.001j))+(e1_vecs[n_1,0]*e1_vecs[n_1,k]*e_vecs[2*n_2+1,0]*e_vecs[2*n_2+1,l])**2*(1.0/(w_list[i]-(E0-e_vals[l]-k*w_b+b*w_b)+0.001j))
                                    n_2+=1
                                    stop_4=time.time()-now_4
                                    time.sleep(1.0-stop_4)
                            n_1+=1
                            stop_3=time.time()-now_3
                            time.sleep(1.0-stop_3)
                    l+=1
                    stop_2=time.time()-now_2
                    time.sleep(1.0-stop_2)
            k+=1
            stop_1=time.time()-now_1
            time.sleep(1.0-stop_2)
    chi_on.append(chi_2.imag)

但是我的方法不起作用......你有什么好的建议吗?我是编程的初学者......

2 个答案:

答案 0 :(得分:0)

尝试使用

delay = 100  # some time in seconds
start_time = time.time()


while True:
    if start_time + (delay * 5) >= time.time():
         break
    while True:
         if start_time + (delay * 4) >= time.time():
             break
         while True:
             ...
             ...

答案 1 :(得分:0)

time.sleep是错误的使用方法,睡眠需要几秒钟,然后强制程序等待这段时间。相反,如果你花了太长时间,你只是希望你的while循环不运行。

尝试类似:

MAX_TIMEOUT = 100 # Max seconds before we abort

stop_time = time.time() + MAX_TIMEOUT

nw=1000
abort = False
for i in range(nw):
    w_list.append(-3+0.006*i)
    chi_1=0
    chi_2=0
    k=1
    while k<10 and not abort:
        l=1
        while l<10 and not abort:
            n_1=0
            while n_1<10 and not abort:
                n_2=0
                while n_2<5 and not abort:
                    chi_2+=(e1_vecs[n_1,0]*e1_vecs[n_1,k]*e_vecs[2*n_2,0]*e_vecs[2*n_2,l])**2*(1.0/(w_list[i]+(E0-e_vals[l]-k*w_b+b*w_b)-0.001j))+(e1_vecs[n_1,0]*e1_vecs[n_1,k]*e_vecs[2*n_2+1,0]*e_vecs[2*n_2+1,l])**2*(1.0/(w_list[i]-(E0-e_vals[l]-k*w_b+b*w_b)+0.001j))
                    n_2+=1

                    # We check here if we need to abort
                    if time.time() >= stop_time:
                        abort = True # This will force the while loops to end
                        print 'Aborted because we took too long!' #Probably a good idea to log this somewhere
                n_1+=1
            l+=1
        k+=1
    chi_on.append(chi_2.imag)

    if abort:
         break #No point staying in the forloop if we need to abort