You could use celery signals, functions registered will be called before and after a task is executed, it is trivial to measure elapsed time:
from time import time
from celery.signals import task_prerun, task_postrun
d = {}
@task_prerun.connect
def task_prerun_handler(signal, sender, task_id, task, args, kwargs, **extras):
d[task_id] = time()
@task_postrun.connect
def task_postrun_handler(signal, sender, task_id, task, args, kwargs, retval, state, **extras):
try:
cost = time() - d.pop(task_id)
except KeyError:
cost = -1
print task.__name__, cost
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…