如何在cProfile中省略all/any等方法以简化性能分析调用图
调用图中过滤all/any内置函数节点的实现方案
方案1:直接在gprof2dot生成阶段过滤(无需修改代码)
这是成本最低的方案,生成调用图时直接通过内置参数排除all、any节点即可:
gprof2dot -f pstats foo.prof --exclude 'builtins.all' --exclude 'builtins.any' | dot -Tpng -o output.png
处理后调用图会直接跳过all/any节点,上游调用方会直接关联到实际执行的生成器内函数,不会出现多路径汇聚拆分的问题。
方案2:自定义Profile类在采集阶段过滤
你示例代码中的OmittingProfile可以通过继承cProfile.Profile实现,采集阶段就排除all/any的调用统计,适合需要统一过滤规则、多次生成分析结果的场景:
import cProfile import pstats class OmittingProfile(cProfile.Profile): def getstats(self): stats, total_call_time = super().getstats() # 过滤掉all、any内置函数的统计项 filtered_stats = [ entry for entry in stats if entry.code.co_name not in ('all', 'any') ] return filtered_stats, total_call_time
把上述类替换你示例中的占位类即可,生成的foo.prof文件本身就不会包含all、any的调用记录,后续任意分析工具读取该文件都不会出现对应节点。
方案3:预处理已生成的prof文件
如果已经跑完性能测试不想重新执行,可以直接用pstats模块处理已有的prof文件,过滤后再导出:
import pstats # 读取原始prof文件 p = pstats.Stats("foo.prof") # 移除all、any相关条目 all_calls = [call for call in p.stats.keys() if call[2] in ('all', 'any')] for call in all_calls: del p.stats[call] # 保存过滤后的prof文件 p.dump_stats("filtered_foo.prof")
后续用filtered_foo.prof生成调用图即可得到无all/any节点的结果。

内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

