Is there a way in python to check for how long a line of code has been running? Also, if it exceeds a time limit, terminate it.
Problem
It is difficult to explain the entire use case. I have a library which classifies an image in dog and cat for example. I can't modify the original library as it generates so many different errors. So what I'm using is a single function call from that library.
Now, let's say the function call takes variable time to spit out the result for different images. I want to limit the time to 15 seconds, i.e., if any call takes 15 seconds or less then it should run normally, but if it exceeds 15 seconds, then terminate the line and exit.
Example
time.sleep()
can be used as an example to mimic the use case. The equivalent for my problem would be, I want time.sleep(14)
to run successfully, but time.sleep(16)
should terminate after 15 seconds and not finish.
What I've tried
I've tried using Process
from multiprocessing
but I could only return if the line takes enough time or exceeds the limit, I couldn't run the function explicitly. I have the following code to check if it runs in time or not:
def run_with_limited_time(func, args, time):
p = Process(target=func, args=args)
p.start()
p.join(time)
if p.is_alive():
p.terminate()
return False
return True
But don't know how to get the output of actual function call.