How to shut down a program after a given time in Python

I would like my Python program to run the algorithm for a given number of seconds, and then print the best result to the end to the end.

What is the best way to do this?

I tried the following, but it did not work (the program continued to work after 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 
+4
source share
4 answers

Unconfirmed 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 
+4
source

On unix, you can use signals - this code expires after 1 second and counts how many times iterates through the while loop during this 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 can easily get your alarm_handler to throw an exception, which you then catch outside the while loop, print the best result.

+2
source

If you want to do this with threads, a good way is to use Event . Please note that signal.alarm will not work on Windows, so I believe that threads are your best bet, if only in this 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) 
0
source

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

-1
source

All Articles