just like the title says is it possible to time a function's duration and stop it if it reaches a certain duration in python 3.7, sorry if this question is stupid im new and have tried looking for how in google and other stackoverflow questions but i haven't found anything that answers my question
Asked
Active
Viewed 38 times
2
-
Does this answer your question? [How to limit execution time of a function call?](https://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call) – homer Nov 13 '21 at 09:01
1 Answers
0
I took the fibonacci sequence as the example function. This will solve your problem:
#fibonacci sequence
def fibonacci(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
#stop the function if it takes longer than 20 seconds
def fib_timeout(n):
import signal
import time
def handler(signum, frame):
raise Exception('Timeout')
signal.signal(signal.SIGALRM, handler)
signal.alarm(20)
try:
return fib(n)
except:
return 'Timeout'
finally:
signal.alarm(0)
fib_timeout(100000000000000)
(After 20 seconds) --> 'Timeout'

Maximilian Freitag
- 939
- 2
- 10
- 26
-
your answers seems to be the correct one for my question but i am getting AttributeError: module 'signal' has no attribute 'SIGALRM' for some reason – Crisóstomo Musa Nov 13 '21 at 09:53
-
@CrisóstomoMusa Here is the google colab file --> https://colab.research.google.com/drive/1LgorMKkQ-zgDFs_eI1aIOLmTcNj9mKCm?usp=sharing ... so we have a common ground. Run both cells and wait 20 seconds. It would be great if you could mark it as correct. – Maximilian Freitag Nov 13 '21 at 10:24