Skip to content

Instantly share code, notes, and snippets.

@jhorman
Created March 29, 2011 02:42
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 jhorman/891721 to your computer and use it in GitHub Desktop.
Save jhorman/891721 to your computer and use it in GitHub Desktop.
Times a method that may or may not return a deferred
def time_method(stat_name):
"""
Attaches a timeout to the deferred returned by the wrapped function.
After timeout seconds the deferred is canceled and an exception raised.
"""
def attach_timing(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
start = time()
# method for recording the timing in the stats object
def record(result, start):
end = time() - start
statistics.add_timing(stat_name, end*1000.0)
return result
deferred = False
try:
result = method(self, *args, **kwargs)
if isinstance(result, Deferred):
deferred = True
result.addBoth(record, start=start)
return result
finally:
if not deferred:
record(None, start)
return wrapper
return attach_timing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment