4

我希望我的 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
4

4 回答 4

4

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
于 2012-07-09T21:20:11.193 回答
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 循环之外捕获该异常,打印出您的最佳结果。

于 2012-07-09T21:23:14.543 回答
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)
于 2012-07-09T21:31:22.203 回答
-1

You need an exit condition, or the program will run forever (or until it runs out of memory). Add one yourself.

于 2012-07-09T21:19:45.283 回答