如何让函数在没有睡眠的情况下运行特定的秒数

时间:2015-12-11 05:25:31

标签: python-3.x

考虑以下代码:

def boil():
    print("Boiling")

def cool():
    print("Cooling")
    sleep(2)

start = time.time()   
boil()
cool()
boil()
cool()
print(round(time.time()-start)," secs")

我希望boil()函数在不使用sleep()的情况下运行3秒,以便最终输出为10秒。我怎么能这样做?

注意:我正在创建两组代码来说明顺序和并发。因此我不想在boil()中使用sleep(),因为当我使用下面的线程时它会使它并发,这样代码可以更快地执行2秒:

def boil():
    print("Boiling")

def cool():
    print("Cooling")
    sleep(2)

start = time.time()   
boil()
#Here I am cooling and cooking concurrently
Thread(target=cool).start()
boil()
cool()
print(round(time.time()-start)," secs")

1 个答案:

答案 0 :(得分:1)

我想你可以尝试这样的事情。使用time.clock()代替

import time

def boil():
    print("Boiling")
    b_start = time.clock()
    b_end = time.clock()
    while b_end - b_start < 3: # 3 second delay
        b_end = time.clock()

def cool():
    print("Cooling")
    time.sleep(2)


start = time.clock()
end = time.clock()

while end - start < 10: # runs for 10 seconds
    boil()
    cool()
    end = time.clock()

print(round(time.clock()-start)," secs")

#Output
Boiling
Cooling
Boiling
Cooling
10  secs