如何配置pytest-profiling忽略自身函数,仅统计自定义包性能?
解决pytest-profiling只展示自定义包性能数据的方法
方法一:生成统计文件后过滤
先执行命令生成完整的性能统计文件:
pytest --profile --profile-save=profile.stats
再通过Python的pstats模块过滤出仅属于你自定义包的条目(将my_package替换为你的包名):
import pstats stats = pstats.Stats('profile.stats') # 过滤出包含自定义包路径的统计项 stats.filter_path(['my_package']) # 按累计耗时排序并打印结果 stats.sort_stats('cumulative').print_stats()
方法二:使用--profile-restrict参数直接过滤
如果你的pytest-profiling版本支持,可直接通过--profile-restrict参数指定过滤规则,仅展示自定义包的内容:
pytest --profile --profile-restrict="*/my_package/*"
(将my_package替换为你的实际包名)
方法三:在测试代码中针对性 profiling
绕过pytest框架的干扰,直接在测试用例里对自定义代码块做性能分析:
import cProfile import pstats import my_package # 导入你的自定义包 def test_custom_function(): pr = cProfile.Profile() pr.enable() # 执行你需要分析的自定义代码 my_package.target_function() pr.disable() # 整理并打印统计结果 stats = pstats.Stats(pr) stats.sort_stats('cumulative').print_stats()
内容的提问来源于stack exchange,提问作者Daniel Walker
相关产品推荐
相关产品推荐

