進(jìn)行性能優(yōu)化首先要分析性能(也就是運(yùn)行時(shí)間)的瓶頸,以獲得最大加速比。程序中也符合二八法則,即20%的代碼需要80%的時(shí)間,甚至更加極端,某一段代碼的小幅提升在上萬(wàn)次的調(diào)用中是性能質(zhì)的飛躍。
分析函數(shù)運(yùn)行情況的工具包包括cprofile, line_profile,timeit,當(dāng)然也可以直接用time包手寫定義自己需要的。
注意,cprofile無(wú)法用于多線程,會(huì)有pickle錯(cuò)誤。 逐行分析定位比較好用的有:line_profiler。
Timeit
https://docs.python.org/2/library/timeit.html
Jupyter 里小程序用很好用 %timeit,
一個(gè)cell 或者一行代碼的簡(jiǎn)單示范
%%timeit
for i in range(100):
pass
輸出
1.56 μs ± 38.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
命令行中使用的簡(jiǎn)單示范
$ python3 -m timeit '"-".join(str(n) for n in range(100))'
10000 loops, best of 3: 30.2 usec per loop
$ python3 -m timeit '"-".join([str(n) for n in range(100)])'
10000 loops, best of 3: 27.5 usec per loop
$ python3 -m timeit '"-".join(map(str, range(100)))'
10000 loops, best of 3: 23.2 usec per loop
Line profile
if __name__ == "__main__":
prof = LineProfiler() # create profile object
prof.enable()
prof.add_module(train_opt) # module to be analysed
prof.add_function(main) # module to be analysed
prof.add_function(run_one_game)
wrapper = prof(run_one_game)
wrapper(namemark,ncpu,phi,game)
prof.disable()
prof.print_stats(sys.stdout)
Cprofile
1.1 命令行
# 直接把分析結(jié)果打印到控制臺(tái)
python -m cProfile test.py
# 把分析結(jié)果保存到文件中
python -m cProfile -o result.out test.py
# 增加排序方式
python -m cProfile -o result.out -s cumulative test.py
代碼內(nèi)置使用方式
if __name__ == "__main__":
import cProfile
*# 直接把分析結(jié)果打印到控制臺(tái)*
cProfile.run("test()")
*# 把分析結(jié)果保存到文件中*
cProfile.run("test()", filename="result.out")
*# 增加排序方式*
cProfile.run("test()", filename="result.out", sort="cumulative")
1.2 分析工具
使用cProfile分析的結(jié)果可以輸出到指定的文件中,但是文件內(nèi)容是以二進(jìn)制的方式保存的,用文本編輯器打開時(shí)亂碼。所以,Python提供了一個(gè)pstats模塊,用來分析cProfile輸出的文件內(nèi)容。
import pstats
?
# 創(chuàng)建Stats對(duì)象
p = pstats.Stats("result.out")
?
# strip_dirs(): 去掉無(wú)關(guān)的路徑信息
# sort_stats(): 排序,支持的方式和上述的一致
# print_stats(): 打印分析結(jié)果,可以指定打印前幾行
?
# 和直接運(yùn)行cProfile.run("test()")的結(jié)果是一樣的
p.strip_dirs().sort_stats(-1).print_stats()
?
# 按照函數(shù)名排序,只打印前3行函數(shù)的信息, 參數(shù)還可為小數(shù),表示前百分之幾的函數(shù)信息
p.strip_dirs().sort_stats("name").print_stats(3)
?
# 按照運(yùn)行時(shí)間和函數(shù)名進(jìn)行排序
p.strip_dirs().sort_stats("cumulative", "name").print_stats(0.5)
?
# 如果想知道有哪些函數(shù)調(diào)用了sum_num
p.print_callers(0.5, "sum_num")
?
# 查看test()函數(shù)中調(diào)用了哪些函數(shù)
p.print_callees("test")
結(jié)果類似:
8 function calls in 0.042 seconds
?
Ordered by: cumulative time
?
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.042 0.042 test.py:5(<module>)
1 0.002 0.002 0.042 0.042 test.py:12(test)
2 0.035 0.018 0.039 0.020 test.py:5(sum_num)
3 0.004 0.001 0.004 0.001 {range}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
其中,輸出每列的具體解釋如下:
ncalls:表示函數(shù)調(diào)用的次數(shù);
tottime:表示指定函數(shù)的總的運(yùn)行時(shí)間,除掉函數(shù)中調(diào)用子函數(shù)的運(yùn)行時(shí)間;
percall:(第一個(gè)percall)等于 tottime/ncalls;
cumtime:表示該函數(shù)及其所有子函數(shù)的調(diào)用運(yùn)行的時(shí)間,即函數(shù)開始調(diào)用到返回的時(shí)間;
percall:(第二個(gè)percall)即函數(shù)運(yùn)行一次的平均時(shí)間,等于 cumtime/ncalls;
filename:lineno(function):每個(gè)函數(shù)調(diào)用的具體信息;
其他允許的排序方式:calls, cumulative, file, line, module, name, nfl, pcalls, stdname, time等。