[英]How to end program running after given time in Python
我希望我的Python程序在給定的秒數內運行算法,然后輸出到目前為止最好的結果並結束。
最好的方法是什么?
我嘗試了以下操作,但不起作用(打印后程序繼續運行):
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
未經測試的代碼,但是像這樣?
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
在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.
或者,您可以輕松地使alarm_handler引發一個異常,然后將其捕獲到while循環之外,從而輸出最佳結果。
如果要使用線程執行此操作,一個好方法是使用Event
。 請注意, 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)
您需要退出條件,否則程序將永遠運行(或直到內存耗盡)。 自己添加一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.