Skip to content

Instantly share code, notes, and snippets.

@antonagestam
Created February 5, 2019 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonagestam/8e61e6a6bce2bd4f0fb38613b9c628a1 to your computer and use it in GitHub Desktop.
Save antonagestam/8e61e6a6bce2bd4f0fb38613b9c628a1 to your computer and use it in GitHub Desktop.
Decorator for time limiting function calls in Python
import multiprocessing
import functools
import logging
from typing import Callable
class TimeLimitExceeded(Exception):
pass
def time_limited(time_limit: int) -> Callable:
def decorator(fn: Callable) -> Callable:
"""
Run the decorated function in a separate process, and kill it after time
limit is exceeded. If the time limit is exceeded we raise an exception.
"""
@functools.wraps(fn)
def wrapper(*args, **kwargs):
p = multiprocessing.Process(target=fn, args=args, kwargs=kwargs)
p.start()
p.join(time_limit)
if p.is_alive():
logging.error(f"{fn} is still running, terminating ...")
try:
p.terminate()
p.join()
finally:
raise TimeLimitExceeded(
f"{fn.__name__} exceeded time limit of {time_limit} "
f"seconds")
return wrapper
return decorator
instant = time_limited(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment