小编Lau*_*ura的帖子

如何在Python中创建可选的装饰器

我有一组python脚本,我想用kernprof https://github.com/rkern/line_profiler进行分析,但我也希望能够在没有kernprof的正常执行期间运行它.

在没有kernprof的情况下执行期间忽略未定义的@profile的优雅方法是什么?或任何其他装饰.

示例代码:

    @profile
    def hello():
        print('Testing')

    hello()
Run Code Online (Sandbox Code Playgroud)

运行:

    kernprof -l test.py
Run Code Online (Sandbox Code Playgroud)

在@profile方法上正确执行探查器

运行:

    python test.py 
Run Code Online (Sandbox Code Playgroud)

返回错误:

    Traceback (most recent call last):
    File "test.py", line 1, in <module>
    @profile
    NameError: name 'profile' is not defined
Run Code Online (Sandbox Code Playgroud)

希望避免在任何地方捕获此错误,因为我希望代码执行,就好像@profile是一个no-op,而不是用kernprof调用它.

谢谢!-Laura

编辑:我最终使用cProfile与kcachegrind完全避免装饰器.

在KCacheGrind中使用cProfile结果

python -m cProfile -o profile_data.pyprof run_cli.py

pyprof2calltree -i profile_data.pyprof && qcachegrind profile_data.pyprof.log
Run Code Online (Sandbox Code Playgroud)

python profiling python-decorators

4
推荐指数
1
解决办法
466
查看次数

标签 统计

profiling ×1

python ×1

python-decorators ×1