简体   繁体   中英

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.

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:

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.

If you want to do this with threads, a good way is to use an Event . Note that signal.alarm won't work in Windows, so I think threading is your best bet unless in that case.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM