when use Profiler?
有时候你觉得程序运行很慢,想对程序进行优化,但是你又不知道哪部分程序入手,这时候你就需要对程序整体性能进行分析,看看速度慢主要是哪部分程序导致的
why use cProfile?
cProfile,一个python程序性能分析模块。其实Python有两个profiler,Profile和cProfile,前者是纯Python写的,会产生比较大的开销,测试结果不准确。后者是c语言扩展模块,对受测程序影响比较小,所以推荐用cProfile.
how to use cProfile?
首先有以下程序:
from cProfile import Profile
from pstats import Stats
def for1():
y = 0
for i in range(100):
y = y +i
def for2():
y = 0
for i in range(1000000):
y = y + i
def test():
for1()
for2()
现在要对test进行分析:
if __name__ == "__main__":
profiler = Profile() #创建profiler对象
profiler.runcall(test) #对test进行测试
stats = Stats(profiler)
stats.strip_dirs()
stats.sort_stats('cumulative')
stats.print_stats()
结果如下:
4 function calls in 0.192 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.192 0.192 main.py:48(test1)
1 0.192 0.192 0.192 0.192 main.py:43(for2)
1 0.000 0.000 0.000 0.000 main.py:38(for1)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
要分析该结果,我们先要知道几个名词的意思(从左到右)
ncalls:函数在性能分析期间调用的次数
tottime:函数总的运行时间,除去子函数的运行时间
percall:tottime/ncalls
cumtime:该函数包括子函数的累计时间
percall:cumtime/ncalls
filename:lineno(function):函数调用的信息
ok,到这里,你就可以看出来for2函数运行时间是最长的了,因为它cumtime比for1的大。
我们还使用了pstats的Stats类:
stats = Stats(profiler):创建对象
stats.strip_dirs():去掉无关路径信息
stats.sort_stats(‘cumulative’):按累计时间进行排序,也可以按照calls, cumulative,line, module, name, nfl, pcalls, stdname, time进行排序
stats.print_stats():打印统计消息,如果想打印top2的信息,则 stats.print_stats(2)