Skip to content

Instantly share code, notes, and snippets.

@objcode
Created August 9, 2011 09:44
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 objcode/1133680 to your computer and use it in GitHub Desktop.
Save objcode/1133680 to your computer and use it in GitHub Desktop.
signal_timer context manager
import signal
import time
class TimerException(Exception): pass
from contextlib import contextmanager
@contextmanager
def signal_timer(mili):
old = signal.getitimer(signal.ITIMER_REAL)
start = time.time()
tick = float(mili) / 1000.
def timeout(signum, frame):
code = frame.f_code
duration = (time.time() - start) * 1000
signal.setitimer(signal.ITIMER_REAL, 0, 0) # don't race to the reset, we might lose
raise TimerException("Function ran too long %s:%s <%s> (%dms)" % (code.co_name,
frame.f_lineno,
code.co_filename,
duration))
signal.signal(signal.SIGALRM, timeout)
signal.setitimer(signal.ITIMER_REAL, tick, tick)
try:
yield
except TimerException, e:
print str(e)
duration = (time.time() - start)
signal.setitimer(signal.ITIMER_REAL, max(0, old[0] - duration), old[1])
with signal_timer(500):
with signal_timer(50):
i = 0
while True:
i += 1
if i % 100000 == 0:
print "yes"
while True:
i += 1
@objcode
Copy link
Author

objcode commented Aug 9, 2011

yes
yes
Function ran too long module:37 testsignal.py (50ms)
Function ran too long module:39 testsignal.py (500ms)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment