Python中性能分析利器pyinstrument詳細(xì)講解
一、前言
程序的性能也是非常關(guān)鍵的指標(biāo),很多時候你的代碼跑的快,更能夠體現(xiàn)你的技術(shù)。最近發(fā)現(xiàn)很多小伙伴在性能分析的過程中都是手動打印運(yùn)行時間的方式來統(tǒng)計代碼耗時的:
import datetime start=datetime.datetime.now() b=[i for i in range(10000000)] # 生成長度為一千萬的列表 end=datetime.datetime.now() print(end-start)
輸出結(jié)果
0:00:00.377766
這種方法使用很快捷,但需要統(tǒng)計每行代碼的執(zhí)行時間,生成可視化的報告等更完善的性能分析時就有點(diǎn)力不從心了。這個時候可以使用python的第三方庫Pyinstrument
來進(jìn)行性能分析。
二、Pyinstrument使用
Pyinstrument 是一個 Python 分析器。分析器是一種幫助您優(yōu)化代碼的工具 - 使其更快。要獲得最大的速度提升。
Pyinstrument 官方文檔:pyinstrument
Pyinstrument 安裝:
pip install pyinstrument
1. 舉例
對于最開始我們舉的例子,使用Pyinstrument實現(xiàn)的代碼如下:
文末添加個人VX,獲取資料和免費(fèi)答疑 from pyinstrument import Profiler profiler=Profiler() profiler.start() b=[i for i in range(10000000)]# 生成長度為一千萬的列表 profiler.stop() profiler.print()
輸出結(jié)果
_ ._ __/__ _ _ _ _ _/_ Recorded: 10:39:54 Samples: 1
/_//_/// /_\ / //_// / //_'/ // Duration: 0.385 CPU time: 0.391
/ _/ v4.1.1
Program: D:/code/server/aitestdemo/test2.py
0.385 <module> test2.py:2 #執(zhí)行總耗時
└─ 0.385 <listcomp> test2.py:7 #單行代碼耗時
打印的信息包含了記錄時間、線程數(shù)、總耗時、單行代碼耗時、CPU執(zhí)行時間等信息。
在多行代碼分析的情況下的使用效果(分別統(tǒng)計生成一千萬長度、一億長度、兩億長度的列表耗時):
from pyinstrument import Profiler profiler = Profiler() profiler.start() a = [i for i in range(10000000)] # 生成長度為一千萬的列表 b = [i for i in range(100000000)] # 生成長度為一億的列表 c = [i for i in range(200000000)] # 生成長度為十億的列表 profiler.stop() profiler.print()
輸出結(jié)果
Program: D:/code/server/aitestdemo/test2.py
16.686 <module> test2.py:1
├─ 12.178 <listcomp> test2.py:9
├─ 4.147 <listcomp> test2.py:8
└─ 0.358 <listcomp> test2.py:7
2. Pyinstrument分析django代碼
使用Pyinstrument分析 Django 代碼非常簡單,只需要在 Django 的配置文件settings.py
的 MIDDLEWARE
中添加如下配置:
MIDDLEWARE = [ ... 'pyinstrument.middleware.ProfilerMiddleware', ... ]
然后就可以在 url 上加一個參數(shù) profile 就可以:
Pyinstrument還支持flask、異步代碼的性能分析,具體可以查看官方文檔進(jìn)行學(xué)習(xí)。
Pyinstrument也提供了豐富的api供我們使用,官網(wǎng)文檔有詳細(xì)的介紹:https://pyinstrument.readthedocs.io/en/latest/reference.html
三、Pyinstrument與cProfile(python自帶性能分析器)的不同
根據(jù)官方文檔的描述來看,Pyinstrument的系統(tǒng)開銷會比cProfile 這類跟蹤分析器小很多,cProfile由于大量調(diào)用探查器,可能會扭曲測試結(jié)果:
總結(jié)
到此這篇關(guān)于Python中性能分析利器pyinstrument詳細(xì)講解的文章就介紹到這了,更多相關(guān)Python性能分析利器pyinstrument內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python中三種高階函數(shù)(map,reduce,filter)詳解
在Python中,函數(shù)其實也是一種數(shù)據(jù)類型,今天重點(diǎn)給大家介紹python中三種高階函數(shù)(map,reduce,filter)的相關(guān)知識,感興趣的朋友一起看看吧2021-10-10Python 實現(xiàn)大整數(shù)乘法算法的示例代碼
這篇文章主要介紹了Python 實現(xiàn)大整數(shù)乘法算法的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09