Python性能分析 (Profiling)

性能分析(Profiling)可用於分析程序的運行時間主要消耗在何處,以便有效優化程序的運行效率。php

Profiling可分爲兩步,一是運行程序收集程序不一樣部分運行時間的數據,二是數據的可視化和分析。html

Hint.gif
提示: 
本文介紹的方法主要針對類Linux系統,部分工具在Windows等系統 可能也能使用。

目錄

[隱藏]

Python Profiling數據採集

cProfile

Python的cProfile模塊可用於數據採集,適用於Python 2和Python 3。其調用方法很簡單:python

import cProfile# 如下調用將運行函數somefunc(),並將相關數據記錄到log_file.pyprof cProfile.run('somefunc()', 'log_file.pyprof')

更多信息請參考Python Profiler文檔linux

有些小程序也能夠直接從命令行調用cProfile模塊執行[1]小程序

python -m cProfile -o profile_data.pyprof script_to_profile.py

hotshot

hotshot是高性能的Profiling數據採集工具,其運行時對程序效率的影響很小,但會產生巨大的運行記錄,分析也比較慢。[2] Python 3中沒有hotshot。故如無特殊需求,請使用cProfile。bash

import hotshot profiler = hotshot.Profile("hotshot.log") profiler.run('trackStereo.solveStereoNew()')

數據可視化

Gprof2Dot

Gprof2Dot的輸出,經dot命令渲染後的圖片。

Gprof2Dot可將多種Profiler的數據轉成Graphviz可處理的圖像表述。配合dot命令,便可獲得不一樣函數所消耗的時間分析圖。以處理cProfile的記錄爲例[3]函數

# 運行程序記錄數據: # python -m cProfile -o profile_data.pyprof path/to/your/script arg1 arg2  # profile_data.pyprof是獲取的數據;dot命令須要安裝Graphviz才能用 gprof2dot.py -f pstats profile_data.pyprof | dot -Tpng -o output.png

Run Snake Run

Run Snake Run截圖

RunSnakeRun是個Python腳本,使用wxPython將Profiler數據可視化,效果如圖。工具

RunSnakeRun還可分析內存佔用,但仍處於實驗階段。[4]性能

KCacheGrind

KCacheGrind可視化Python運行時數據

KCacheGrind是Linux中經常使用的profiling visualization軟件,其默承認處理valgrind的輸出。經過一些腳本也能夠讓其分析cProfile或hotshot記錄下的數據。優化

處理cProfile的數據可以使用pyprof2calltree

# 運行程序記錄數據: # python -m cProfile -o profile_data.pyprof path/to/your/script arg1 arg2  # 使用pyprof2calltree處理數據並自動調用KCacheGrind pyprof2calltree -i profile_data.pyprof -k

處理hotshot的數據可以使用KCacheGrind中的hotshot2calltree命令:

# 使用hotshot2calltree處理數據,完成後需手動在KCacheGrind中打開輸出文件 hotshot2calltree hotshot.log -o hs_calltree.log
Note.gif
注意:  KCacheGrind雖然功能強大,但其輸出的分析樹彷佛並不完整,若是您瞭解緣由,請補充。
相關文章
相關標籤/搜索