Skip to content

Instantly share code, notes, and snippets.

@hamsolodev
Created June 5, 2010 05:31
Show Gist options
  • Save hamsolodev/426337 to your computer and use it in GitHub Desktop.
Save hamsolodev/426337 to your computer and use it in GitHub Desktop.
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
from celery.task import Task
class AddTwoNumbers(Task):
@timed_task
def run(self, num1, num2):
return num1 + num2
>>> from django.core.cache import cache
>>> timings = cache.get('AddTwoNumbers.timings')
>>> sum(timings) / len(timings)
0.268
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