Python cProfile - 花在方法上的大部分时间'启用' ' _lsprof.Profiler'

时间:2017-08-18 19:34:01

标签: python cprofile

我正在尝试对一个相当复杂的Python程序进行一些高级分析。但是,使用cProfile时,几乎所有时间都是以:

衡量的

import java.io.IOException; public class ControlFlowTest { public static void main(String[] args) throws java.io.IOException { char ch ; Scanner scanner= new Scanner(System.in); do { ch = scanner.next().charAt(0); } while(ch != '.'); } }

如果我分析整个程序{method 'enable' of '_lsProf.Profiler' objects}以及在Python代码中执行分析(使用python -m cProfile ...

,就会发生这种情况。

指向我可能做错的任何指示?

2 个答案:

答案 0 :(得分:2)

这是因为代码中的某个地方有类似

的内容
import cProfile
pr = cProfile.Profile()
pr.enable()

用于手动保存结果或打印结果,如果您像调用python -m cProfile -o program.prof my_program.py那样调用分析器,则不需要在程序中使用cProfile。

答案 1 :(得分:0)

这看起来像是错误或限制。嵌套的探查器不起作用。这是一个复制品:

import cProfile
import pstats
import time
import cStringIO as StringIO

def do():
    for i in range(100):
       time.sleep(0.01)

def do_more():
    for i in range(100):
        time.sleep(0.01)

def do_all():
    all_profiler = cProfile.Profile()
    all_profiler.enable()

    profiler = cProfile.Profile()
    profiler.enable()

    do()

    profiler.disable()
    strio = StringIO.StringIO()
    stats = pstats.Stats(profiler, stream=strio)
    stats.sort_stats("cumulative")
    stats.print_stats(10)
    print "do profile:\n{}".format(strio.getvalue())

    do_more()

    all_profiler.disable()
    strio = StringIO.StringIO()
    stats = pstats.Stats(all_profiler, stream=strio)
    stats.sort_stats("cumulative")
    stats.print_stats(10)
    print "all profile:\n{}".format(strio.getvalue())


do_all()

添加到tmp.py并在shell中运行,输出为:

do profile:
         103 function calls in 1.009 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.009    1.009 tmp.py:6(do)
      100    1.008    0.010    1.008    0.010 {time.sleep}
        1    0.000    0.000    0.000    0.000 {range}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}



all profile:
         1 function calls in 2.018 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    2.018    2.018    2.018    2.018 {method 'enable' of '_lsprof.Profiler' objects}

请注意,“ all_profiler”仅显示另一个探查器。

编辑:可能这只是摘要打印的问题。我没有尝试将统计信息转储以与配置文件查看器一起使用,例如转换为与kCachegrind一起使用。