【问题标题】:Python cProfile - most of time spent in method 'enable' of '_lsprof.Profiler'Python cProfile - 大部分时间花在“_lsprof.Profiler”的“启用”方法上
【发布时间】:2018-01-27 13:36:31
【问题描述】:

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

{method 'enable' of '_lsProf.Profiler' objects}

如果我分析整个程序 python -m cProfile ... 以及在 Python 代码中执行分析(使用 profile.enable()/.disable()/.create_stats...),就会发生这种情况

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

【问题讨论】:

    标签: python cprofile


    【解决方案1】:

    这是因为在你的代码中的某个地方你有类似的东西

    import cProfile
    pr = cProfile.Profile()
    pr.enable()
    

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

    【讨论】:

    • 这并没有解决问题(至少对我来说不是很清楚)。我也见过同样的事情。我没有得到正在执行的配置文件,而是得到了原始帖子中提到的一行。换句话说,分析器似乎吞下了它应该分析的东西。
    【解决方案2】:

    这看起来像是一个错误或限制。嵌套分析器不起作用。这是一个再现:

    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 一起使用。

    【讨论】:

      猜你喜欢
      • 2011-05-28
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多