Python cprofile filename:lineno 获取完整路径

use*_*754 8 python cprofile

我曾经cprofile得到高罪犯,但是filename:lineno只列出文件名,但是列出文件路径对于快速打开该路径会更有用。特别是如果不同层次结构中可能存在相同的模块名称。

ncalls    tottime    percall    cumtime    percall    filename:lineno(function)
1         0.000       0.000       3.922    display.py:599 (show)
Run Code Online (Sandbox Code Playgroud)

有没有办法把它变成全路径?

小智 7

我猜你用“pstats.Stats”类格式化输出,并且你有:

stats = Stats(profiler)
stats.strip_dirs()  # remove this
Run Code Online (Sandbox Code Playgroud)

  • 如果 cProfiler 从终端运行怎么办? (7认同)

mar*_*xin 5

如果您从终端运行,请添加 -o 标志:

python -m cProfile -o output.data your_script.py ...
Run Code Online (Sandbox Code Playgroud)

然后从控制台:

import pstats
ps = pstats.Stats('output.data')
ps.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(20)
Run Code Online (Sandbox Code Playgroud)

您应该得到如下输出:

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>)
      ...
Run Code Online (Sandbox Code Playgroud)