定位程序性能瓶頸
對代碼優化的前提是需要了解性能瓶頸在什么地方,程序運行的主要時間是消耗在哪里,對於比較復雜的代碼可以借助一些工具來定位,python 內置了豐富的性能分析工具,如 profile,cProfile 與 hotshot 等。其中 Profiler 是 python 自帶的一組程序,能夠描述程序運行時候的性能,並提供各種統計幫助用戶定位程序的性能瓶頸。Python 標准模塊提供三種 profilers:cProfile,profile 以及 hotshot。
profile 的使用非常簡單,只需要在使用之前進行 import 即可。具體實例如下:
使用 profile 進行性能分析
1 import profile 2 def profileTest(): 3 Total =1; 4 for i in range(10): 5 Total=Total*(i+1) 6 print Total 7 return Total 8 if __name__ == "__main__": 9 profile.run("profileTest()")
程序的運行結果如下:
圖 1. 性能分析結果
其中輸出每列的具體解釋如下:
●ncalls:表示函數調用的次數;
●tottime:表示指定函數的總的運行時間,除掉函數中調用子函數的運行時間;
●percall:(第一個 percall)等於 tottime/ncalls;
●cumtime:表示該函數及其所有子函數的調用運行的時間,即函數開始調用到返回的時間;
●percall:(第二個 percall)即函數運行一次的平均時間,等於 cumtime/ncalls;
●filename:lineno(function):每個函數調用的具體信息;
如果需要將輸出以日志的形式保存,只需要在調用的時候加入另外一個參數。如 profile.run(“profileTest()”,”testprof”)。