Python cprofile 文件名:行号 获取完整路径

11

我使用cprofile获取高耗时函数,但是filename:lineno仅列出文件名,如果同时存在不同层次的相同模块名称,将会更有用地快速打开该路径。

ncalls    tottime    percall    cumtime    percall    filename:lineno(function)
1         0.000       0.000       3.922    display.py:599 (show)

有没有选项可以将其转换为完整路径?

3个回答

6
我猜你使用了 "pstats.Stats" 类来格式化输出,你可能有以下代码:
stats = Stats(profiler)
stats.strip_dirs()  # remove this

1
啊,是的,我只是毫无思考地从以下示例中复制了样本:https://docs.python.org/3.6/library/profile.html#instant-user-s-manual - Ciro Santilli OurBigBook.com
5
如果 cProfiler 是从终端运行的,该怎么办? - HosseyNJF

3
如果您是在终端中运行,请添加-o标志:
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>)
      ...

2

似乎没有内置的方法,但你可以这样做:

import cProfile                                                    
import pstats   
                                                   
p = cProfile.Profile()                      
s = p.run("1+1")     
pstats.Stats(s).sort_stats(2).print_stats()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接