1、先分析性能,再进行优化,才能达到性价比最高的优化。
利用下面的2个工具进行分析最占用时间的代码行,然后进行优化
# 不要凭感觉去判断,先获取具体的测评结果
#@ profiler 是纯 python版本,cProfile 是 C 版本(速度更快)
import time
from cProfile import Profile
def test(n=2):
"""测试方法"""
if n < 0:
return
time.sleep(1)
test(n - 1)
pro = Profile()
pro.runcall(test)
from pstats import Stats # 内置统计
stats = Stats(pro)
stats.strip_dirs()
stats.sort_stats('cumulative')
stats.print_stats() # 打印输出
"""
8 function calls (5 primitive calls) in 3.002 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
4/1 0.000 0.000 3.002 3.002 <stdin>:1(test)
3 3.002 1.001 3.002 1.001 {built-in method time.sleep}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
ncalls # 调用次数
tottime # 执行这个函数本身的时间(不包括该函数调用其他函数的时间)
tottime percall # tottime/ncalls ,这个函数的平均时间
cumtime # 执行这个函数花费的总时间(包括该函数调用其他函数的时间)
cumtime percall # cumtime/ncalls ,这个函数的平均总时间
"""
stats.print_callers() # 打印
"""
Ordered by: cumulative time
Function was called by...
ncalls tottime cumtime
<stdin>:1(test) <- 3/1 0.000 2.001 <stdin>:1(test)
{built-in method time.sleep} <- 3 3.002 3.002 <stdin>:1(test)
{method 'disable' of '_lsprof.Profiler' objects} <-
Function # 左边是被调用者,后边是调用者
"""