【发布时间】:2016-01-28 18:37:19
【问题描述】:
我有一组 python 脚本,我想用 kernprof https://github.com/rkern/line_profiler 进行分析,但我也希望能够在没有 kernprof 的情况下在正常执行期间运行它。
在没有kernprof 的情况下,在执行期间忽略未定义的@profile 的优雅方法是什么?或任何其他装饰器。
示例代码:
@profile
def hello():
print('Testing')
hello()
运行:
kernprof -l test.py
在@profile 方法上正确执行分析器
运行:
python test.py
返回错误:
Traceback (most recent call last):
File "test.py", line 1, in <module>
@profile
NameError: name 'profile' is not defined
希望避免在任何地方捕获此错误,因为我希望代码在不使用 kernprof 调用时就好像 @profile 是无操作一样执行。
谢谢! -劳拉
编辑:我最终将 cProfile 与 kcachegrind 一起使用,并完全避免使用装饰器。
Using cProfile results with KCacheGrind
python -m cProfile -o profile_data.pyprof run_cli.py
pyprof2calltree -i profile_data.pyprof && qcachegrind profile_data.pyprof.log
【问题讨论】:
标签: python profiling python-decorators