Created
June 1, 2017 08:12
-
-
Save misza222/93b51e15136e7448b19fb089c3ec51af to your computer and use it in GitHub Desktop.
Iterative deepening timeout example in python for *nix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import signal | |
import time | |
class TimeOut(): | |
""" | |
TimeOut for *nix systems | |
""" | |
class TimeOutException(Exception): | |
pass | |
def __init__(self, sec): | |
self.sec = sec # time we want an exception to be raised after | |
self.start_time = None # to measure actual time | |
def start(self): | |
self.start_time = time.time() | |
signal.signal(signal.SIGALRM, self.raise_timeout) | |
signal.alarm(self.sec) | |
def raise_timeout(self, *args): | |
signal.alarm(0) # disable | |
message = "Alarm set for {}s and actually passed {}s".format(self.sec, round(time.time() - self.start_time, 5)) | |
raise TimeOut.TimeOutException(message) | |
def fibonacci(n): | |
if n < 2: | |
return n | |
return fibonacci(n-2) + fibonacci(n-1) | |
def iterative_deepening(timeout): | |
result = None # we store best result here | |
depth = 1 # depth of the current search | |
try: | |
TimeOut(timeout).start() | |
while True: | |
result = fibonacci(depth) | |
depth += 1 | |
except TimeOut.TimeOutException as e: | |
print(e) # If we are not bothered by nanosecond differences, this is good enough | |
return result, depth | |
if __name__ == '__main__': | |
for timeout in range(1,10): | |
result, depth = iterative_deepening(timeout) | |
print ("After ", timeout, " seconds reached depth is ", depth, " with a result ", result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment