Measuring Celery task execution time

前端 未结 2 1118
不知归路
不知归路 2020-12-16 21:57

I have converted a standalone batch job to use celery for dispatching the work to be done. I\'m using RabbitMQ. Everything is running on a single machine and no other proces

2条回答
  •  被撕碎了的回忆
    2020-12-16 22:42

    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
    

提交回复
热议问题