我可以在 pytest 测试上运行 line_profiler 吗? [英] Can I run line_profiler over a pytest test?
问题描述
我用
py.test --durations=10
我现在想用 line_profiler 或 cprofile 之类的东西来检测其中一个测试.我真的很想从测试本身获取配置文件数据,因为 pytest 设置或拆除很可能是缓慢的一部分.
I would like to instrument one of those tests now with something like line_profiler or cprofile. I really want to get the profile data from the test itself as the pytest setup or tear down could well be part of what is slow.
然而,考虑到 line_profiler 或 cprofile 通常如何参与,我不清楚如何让它们与 pytest 一起工作.
However given how line_profiler or cprofile is typically involved it isn't clear to me how to make them work with pytest.
推荐答案
像这样运行 pytest:
Run pytest like this:
python3 -m cProfile -o profile -m pytest
您甚至可以传入可选参数:
You can even pass in optional arguments:
python3 -m cProfile -o profile -m pytest tests/worker/test_tasks.py -s campaigns
这将在您的当前目录中创建一个名为 profile
的二进制文件.这可以通过 pstats 进行分析:
This will create a binary file called profile
in your current directory. This can be analyzed with pstats:
import pstats
p = pstats.Stats('profile')
p.strip_dirs()
p.sort_stats('cumtime')
p.print_stats(50)
这将打印累积持续时间最长的 50 行.
This will print the 50 lines with the longest cumulative duration.
这篇关于我可以在 pytest 测试上运行 line_profiler 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!