装饰器,它描述方法调用并记录分析结果 [英] A decorator that profiles a method call and logs the profiling result

查看:41
本文介绍了装饰器,它描述方法调用并记录分析结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个装饰器,该装饰器描述方法并记录结果。

I want to create a decorator that profiles a method and logs the result. How can this be done?

推荐答案

装饰器看起来像这样:

import time
import logging

def profile(func):
    def wrap(*args, **kwargs):
        started_at = time.time()
        result = func(*args, **kwargs)
        logging.info(time.time() - started_at)
        return result

    return wrap

@profile
def foo():
    pass

无论如何,如果您想进行一些认真的分析,我建议您使用配置文件或cProfile软件包。

Anyway, if you want to do some serious profiling I would suggest you use the profile or cProfile packages.

这篇关于装饰器,它描述方法调用并记录分析结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆