我使用cprofile
获取高耗时函数,但是filename:lineno
仅列出文件名,如果同时存在不同层次的相同模块名称,将会更有用地快速打开该路径。
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 3.922 display.py:599 (show)
有没有选项可以将其转换为完整路径?
stats = Stats(profiler)
stats.strip_dirs() # remove this
python -m cProfile -o output.data your_script.py ...
然后从控制台执行:
import pstats
ps = pstats.Stats('output.data')
ps.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(20)
Tue Oct 19 07:17:56 2021 output.data
18646457 function calls (18374990 primitive calls) in 30.760 seconds
Ordered by: cumulative time
List reduced from 22652 to 20 due to restriction <20>
ncalls tottime percall cumtime percall filename:lineno(function)
4321/1 0.037 0.000 30.796 30.796 {built-in method builtins.exec}
1 0.000 0.000 30.796 30.796 manage.py:1(<module>)
...
似乎没有内置的方法,但你可以这样做:
import cProfile
import pstats
p = cProfile.Profile()
s = p.run("1+1")
pstats.Stats(s).sort_stats(2).print_stats()