cProfiler:如何按执行顺序获取统计数据?

时间:2014-03-03 11:56:29

标签: python python-2.7 profiling profiler

我希望获取有关分析器的统计信息,并且不按呼叫次数分组,而不是按时间花费,而是按自然执行顺序

例如,如果我们将cProfiler用于下一个简单程序:

def my_sleep0():
    sleep( 0.05 )

def my_sleep1():
    sleep( 0.15 )
    my_sleep2()

def my_sleep2():
    my_sleep3()

def my_sleep3():
    sleep( 0.1 )


if __name__ == '__main__':

    p = Profiler( './' ) # a wrapper for cProfiler, cProfiler starts here

    i = 10

    for i in range( 1, 5 ):
        i += 100
        my_sleep0()
        my_sleep1()
        my_sleep1()

    # cProfiler destructs and ends here

我想通过自然执行顺序获取统计数据,例如:

Ordered by: execution

calling_function    cumtime backtrace

test.py:36(my_sleep0)   <cumtime>  test.py:43()
test.py:39(my_sleep1)   <cumtime>  test.py:44()
test.py:43(my_sleep2)   <cumtime>  test.py:20 called by test.py:44(my_sleep1)
test.py:43(my_sleep3)   <cumtime>  test.py:25 called by test.py:20(my_sleep1)->test.py:26(my_sleep2)
test.py:39(my_sleep1)   <cumtime>  test.py:45()
test.py:43(my_sleep2)   <cumtime>  test.py:20 called by test.py:25(my_sleep1)
test.py:43(my_sleep3)   <cumtime>  test.py:25 called by test.py:20(my_sleep1)->test.py:26(my_sleep2)
...

<cumtime>是数字时间。)

Python有没有办法实现它?怎么样?

的增添。

我的Profiler()代码现在没有这样做:

class Profiler:
    def __init__( self, dir ):
        self._profiler = cProfile.Profile()
        self._profiler.enable()

        self._dir = dir # profiler output is "/tmp/profiler/{key}/<files_here>"


    def stop( self ):
        profilerDir = self._dir

        self._profiler.disable()

        with open( os.path.join( profilerDir, datetime.now().strftime( "%d-%m-%y %H.%M.%S" ) ), 'w' ) as f:
            stat = pstats.Stats( self._profiler, stream = f ).sort_stats( 'pcalls' )
            stat.print_stats()  
            stat.print_callers()
            stat.print_callees()


    def __del__( self ):
        self.stop()

1 个答案:

答案 0 :(得分:1)

是的,但在很多情况下这不是一件明智的事情,因为代码中的一个(慢)部分可能会在执行中被多次调用,你可以做的是运行一个跟踪并使用它的输出对配置文件条目进行排序。

即。 trace告诉您执行的顺序,可以用来对配置文件数据进行排序。

我会认真考虑查看个人资料查看器工具,例如runsnakerun,例如以下内容让我看看花了多少时间以及调用它的位置: enter image description here

相关问题