Created
June 5, 2010 05:31
-
-
Save hamsolodev/426337 to your computer and use it in GitHub Desktop.
This file contains 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
import datetime | |
from collections import deque | |
from functools import wraps | |
from django.core.cache import cache | |
def timed_task(f): | |
@wraps(f) | |
def wrapper(*args, **kwargs): | |
"""Simple decorator to cache previous 10 execution times | |
""" | |
start = datetime.now() | |
rslt = f(*args, **kwargs) | |
diff = datetime.now() - start | |
cache_key = '%s.timings' % args[0].__class__.__name__ | |
last_ten = cache.get(cache_key, deque([], 10)) | |
last_ten.append(diff.seconds + float(diff.microseconds)/1000000) | |
if not cache.add(cache_key, last_ten, 86400): | |
cache.set(cache_key, last_ten, 86400) | |
return rslt | |
return wrapper |
This file contains 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
from celery.task import Task | |
class AddTwoNumbers(Task): | |
@timed_task | |
def run(self, num1, num2): | |
return num1 + num2 |
This file contains 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
>>> from django.core.cache import cache | |
>>> timings = cache.get('AddTwoNumbers.timings') | |
>>> sum(timings) / len(timings) | |
0.268 |
This file contains 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
from django.core.cache import cache | |
from celery.task import Task | |
class AddTwoNumbers(Task): | |
@timed_task | |
def run(self, num1, num2): | |
return num1 + num2 | |
@classmethod | |
def avgtime(cls): | |
timings = cache.get('%s.timings' % cls.__name__, []) | |
try: | |
return sum(timings) / len(timings) | |
except ZeroDivisionError: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment