The greatest glory in living lies not in never falling, but in rising every time we fall.

—— Nelson Mandela

python 中显示profile 火焰图

28 Jul 2016

profile 可以给出了程序总运行时间,还会给出每个函数的运算时间,被调用了多少次。 从而让我们更容易优化我们的程序。 python 中内置的profiler 是cProfile . 而且使用起来很简单。

import cProfile
import re
cProfile.run('re.compile("foo|bar")')

会打印出:

197 function calls (192 primitive calls) in 0.002 seconds
Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 1    0.000    0.000    0.001    0.001 <string>:1(<module>)
 1    0.000    0.000    0.001    0.001 re.py:212(compile)
 1    0.000    0.000    0.001    0.001 re.py:268(_compile)
 1    0.000    0.000    0.000    0.000 sre_compile.py:172(_compile_charset)
 1    0.000    0.000    0.000    0.000 sre_compile.py:201(_optimize_charset)
 4    0.000    0.000    0.000    0.000 sre_compile.py:25(_identityfunction)
 3/1    0.000    0.000    0.000    0.000 sre_compile.py:33(_compile)

表中每一列的含义解释如下: ncalls:它表示该函数被调用的次数。 在递归调用的情况下,它可以有两个用斜杠分隔的数字。 在这种情况下,第一个数字表示包括递归调用在内的总调用,第二个数字表示不包括递归调用的原始调用。
tottime:表示在该功能中花费的总时间,不包括在该功能的子功能中花费的时间。
percall :表示 tottime 除以 ncalls。
cumtime :表示在该函数中花费的总时间,包括在该函数的子函数中花费的时间。
percall :表示 cumtime 除以 ncalls。
filename:lineno(function) :表示文件名、文件中的行号和函数名。

我们也可以对输出 进行排序:

# Sort output by ncalls
if __name__ == '__main__':
    import cProfile, pstats
    profiler = cProfile.Profile()
    profiler.enable()
    main()
    profiler.disable()
   stats = pstats.Stats(profiler).sort_stats('ncalls')
   stats.print_stats()