在Python中,如何在给定时间后结束程序运行
我希望我的Python程序在给定的秒数内运行一个算法,然后打印到目前为止的最佳结果并结束 最好的方法是什么 我尝试了以下操作,但没有成功(打印后程序仍在运行):在Python中,如何在给定时间后结束程序运行,python,multithreading,time,Python,Multithreading,Time,我希望我的Python程序在给定的秒数内运行一个算法,然后打印到目前为止的最佳结果并结束 最好的方法是什么 我尝试了以下操作,但没有成功(打印后程序仍在运行): 您需要一个退出条件,否则程序将永远运行(或直到内存耗尽)。自己添加一个。未经测试的代码,但类似这样的代码 import time threshold = 60 start = time.time() best_run = threshold while time.time()-start < threshold:
您需要一个退出条件,否则程序将永远运行(或直到内存耗尽)。自己添加一个。未经测试的代码,但类似这样的代码
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
导入时间
阈值=60
开始=时间。时间()
最佳运行=阈值
而time.time()-开始<阈值:
run\u start=time.time()
doSomething()
运行时间=时间。时间()-开始
如果运行时间<最佳运行时间:
最佳运行时间=运行时间
在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_处理程序引发一个异常,然后在while循环外捕获该异常,打印最佳结果。如果您希望使用线程执行此操作,一个好方法是使用。请注意,
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)
您是否可以在超时后向其传递一个
SIGINT
,并捕获作为异常的SIGINT
,打印到目前为止的最佳结果,然后在该块内退出?
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)