-1

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

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)

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

4

2 回答 2

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:
             ...
             ...
于 2013-11-07T11:34:17.293 回答
0

time.sleep是错误的使用方法, 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
于 2013-11-07T12:52:44.170 回答