python程式碼執行效能分析工具
阿新 • • 發佈:2022-03-08
Python這7個性能測試工具,你都有了解嗎?
1.timeit:
timeit只輸出被測試程式碼的總執行時間
單位為秒,沒有詳細的統計。
2.profile
profile:純Python實現的效能測試模組,介面和cProfile一樣。
- ncall:函式執行次數
- tottime: 函式的總的執行時間,減去函式中呼叫子函式的執行時間
第一個percall:percall = tottime / nclall
- cumtime:函式及其所有子函式調整的執行時間,也就是函式開始呼叫到結束的時間。
第二個percall:percall = cumtime / nclall
3.cProfile
profile:c語言實現的效能測試模組,介面和profile一樣。
ncalls、tottime、percall、cumtime含義同profile。
4.line_profiler
安裝:
pip install line_profiler
安裝之後kernprof.py會加到環境變數中。
line_profiler可以統計每行程式碼的執行次數和執行時間等,時間單位為微妙。
測試程式碼:
C:Python34 est.py
使用:
- 在需要測試的函式加上@profile裝飾,這裡我們把測試程式碼寫在C:Python34 est.py檔案上.
- 執行命令列:kernprof -l -v C:Python34 est.py
輸出結果如下:
- Total Time:測試程式碼的總執行時間
- Hits:表示每行程式碼執行的次數
- Time:每行程式碼執行的總時間
- Per Hits:每行程式碼執行一次的時間
- % Time:每行程式碼執行時間的百分比
5.memory_profiler:
memory_profiler工具可以統計每行程式碼佔用的記憶體大小。
安裝:
- pip install memory_profiler
- pip install psutil
測試程式碼:
同line_profiler。
使用:
- 在需要測試的函式加上@profile裝飾
- 執行命令: python -m memory_profiler C:Python34 est.py
輸出如下:
6.PyCharm圖形化效能測試工具:
PyCharm提供了影象化的效能分析工具,使用方法見官網
7.objgraph:
objgraph是一個實用模組,可以列出當前記憶體中存在的物件,可用於定位記憶體洩露。
objgraph需要安裝:
pip install objgraph轉載自:https://zhuanlan.zhihu.com/p/83421076