[英]How to end program running after given time in 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. 我希望我的Python程序在给定的秒数内运行算法,然后输出到目前为止最好的结果并结束。
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
On unix, you can use signals -- This code times out after 1 second and counts how many times it iterates through the while loop in that time: 在unix上,您可以使用信号-此代码在1秒钟后超时,并计算在该时间内遍历while循环的次数:
import signal
import sys
def handle_alarm(args):
print args.best_val
sys.exit()
class Foo(object):
pass
self=Foo() #some mutable object to mess with in the loop
self.best_val=0
signal.signal(signal.SIGALRM,lambda *args: handle_alarm(self))
signal.alarm(1) #timeout after 1 second
while True:
self.best_val+=1 # do something to mutate "self" here.
Or, you could easily have your alarm_handler raise an exception which you then catch outside the while loop, printing your best result. 或者,您可以轻松地使alarm_handler引发一个异常,然后将其捕获到while循环之外,从而输出最佳结果。
If you want to do this with threads, a good way is to use an Event
. 如果要使用线程执行此操作,一个好方法是使用
Event
。 Note that signal.alarm
won't work in Windows, so I think threading is your best bet unless in that case. 请注意,
signal.alarm
在Windows中将无法运行,因此除非出现这种情况,否则我认为线程化是您的最佳选择。
import threading
import time
import random
class StochasticSearch(object):
def __init__(self):
self.halt_event = threading.Event()
def find_best_result(self, duration):
halt_thread = threading.Timer(duration, self.halt_event.set)
halt_thread.start()
best_result = 0
while not self.halt_event.is_set():
result = self.search()
best_result = result if result > best_result else best_result
time.sleep(0.5)
return best_result
def search(self):
val = random.randrange(0, 10000)
print 'searching for something; found {}'.format(val)
return val
print StochasticSearch().find_best_result(3)
You need an exit condition, or the program will run forever (or until it runs out of memory). 您需要退出条件,否则程序将永远运行(或直到内存耗尽)。 Add one yourself.
自己添加一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.