2012-07-09 63 views
4

我想让我的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 
+0

你能可能传递一个'SIGINT'您超时后,赶上'SIGINT'作为一个例外,中,到目前为止并退出打印的最好成绩只是块? – inspectorG4dget 2012-07-09 21:20:32

回答

-1

你需要退出条件,否则程序将永远运行(或直到内存用完)。自己添加一个。

4

未经测试的代码,但类似的东西?

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 
2

在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循环之外捕获,打印出你的最佳结果。

0

如果你想用线程做到这一点,一个好方法是使用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) 
相关问题