我想分析python代码的性能,为此我使用了cProfile模块并生成了python文档中提到的.cprof文件。我正在使用pyprof2calltree python 模块将 .cprof 文件打开到KCacheGrind。. 我放了分析结果的截图,它显示名为cycle 5的函数占用了 100.04% 的 CPU 时间。我无法理解这代表什么。它也没有显示此功能的任何源代码。
1 回答
它表明名为 cycle 5 的函数占用了 100.04% 的 CPU 时间。
不,它表明某些“周期 5”和从它调用的所有函数以及从它们调用的所有函数都在使用 100% 的“包含”时间。
<cycle>
不是真正的函数,它是 kcachegrind启发式地尝试从分析格式中获取递归信息的方式(“循环内调用的包容性成本毫无意义”)。这种格式(为 callgrind 定义)没有函数调用序列的确切信息(f1 调用 f2 调用 f3 ...),只存储对调用者-被调用者。此格式仅适用于“Self”时间,但不适用于存在递归时的“Inclusive”(包括所有被调用者时间)。
KCachegrind 允许(并建议)您使用查看菜单关闭“执行周期检测” :https ://kcachegrind.github.io/html/NewsOld.html
循环检测可通过工具栏按钮进行切换。对于 GUI 应用程序,有时关闭循环检测很有用,即使递归调用存在一些可视化错误。
如果没有循环检测<cycle>
,将不会生成合成函数,但某些函数可能具有 >100%“包含”。时间。尝试使用“Self”时间,或格式更好的分析工具(linux perf
, operf
, ocperf.py
; google 的 cpuprofile 和其他使用完整函数调用堆栈的分析格式)。https://github.com/jrfonseca/gprof2dot列出了许多好的格式,它也可以正确地可视化它们(如果有足够的信息)。尝试使用 python 配置文件格式:
蟒蛇配置文件
python -m profile -o output.pstats path/to/your/script arg1 arg2 gprof2dot.py -f pstats output.pstats | dot -Tpng -o output.png
python cProfile(以前称为lsprof)
python -m cProfile -o output.pstats path/to/your/script arg1 arg2 gprof2dot.py -f pstats output.pstats | dot -Tpng -o output.png
python 热门分析器
热点分析器不包含主要功能。请改用 hotshotmain.py 脚本。
hotshotmain.py -o output.pstats path/to/your/script arg1 arg2 gprof2dot.py -f pstats output.pstats | dot -Tpng -o output.png