Created
March 29, 2011 02:42
-
-
Save jhorman/891721 to your computer and use it in GitHub Desktop.
Times a method that may or may not return a deferred
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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