如何在给定时间后终止程序在Python中的运行 [英] How to end program running after given time in Python
本文介绍了如何在给定时间后终止程序在Python中的运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望我的Python程序在给定的秒数内运行算法,然后显示到目前为止的最佳结果并结束.
I'd like my Python program to run an algorithm for a given number of seconds and then to print the best result so far and to end.
这样做的最好方法是什么?
What is the best way to do so?
我尝试了以下操作,但没有成功(打印后程序仍在运行):
I tried the following but it did not work(the program kept running after the printing):
def printBestResult(self):
print(self.bestResult)
sys.exit()
def findBestResult(self,time):
self.t = threading.Timer(time, self.printBestResult)
self.t.start()
while(1):
# find best result
推荐答案
未经测试的代码,但是像这样?
Untested code, but something like this?
import time
threshold = 60
start = time.time()
best_run = threshold
while time.time()-start < threshold:
run_start = time.time()
doSomething()
run_time = time.time() - start
if run_time < best_run:
best_run = run_time
这篇关于如何在给定时间后终止程序在Python中的运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文