您好,登錄后才能下訂單哦!
這篇文章主要介紹了Python中怎么安裝和使用pyinstrument的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Python中怎么安裝和使用pyinstrument文章都會(huì)有所收獲,下面我們一起來看看吧。
程序的性能也是非常關(guān)鍵的指標(biāo),很多時(shí)候你的代碼跑的快,更能夠體現(xiàn)你的技術(shù)。最近發(fā)現(xiàn)很多小伙伴在性能分析的過程中都是手動(dòng)打印運(yùn)行時(shí)間的方式來統(tǒng)計(jì)代碼耗時(shí)的:
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)計(jì)每行代碼的執(zhí)行時(shí)間,生成可視化的報(bào)告等更完善的性能分析時(shí)就有點(diǎn)力不從心了。這個(gè)時(shí)候可以使用python的第三方庫Pyinstrument
來進(jìn)行性能分析。
Pyinstrument 是一個(gè) Python 分析器。分析器是一種幫助您優(yōu)化代碼的工具 - 使其更快。要獲得最大的速度提升。
Pyinstrument 官方文檔:pyinstrument
Pyinstrument 安裝:
pip install pyinstrument
1. 舉例
對(duì)于最開始我們舉的例子,使用Pyinstrument實(shí)現(xiàn)的代碼如下:
文末添加個(gè)人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í)行總耗時(shí) └─ 0.385 <listcomp> test2.py:7 #單行代碼耗時(shí)
打印的信息包含了記錄時(shí)間、線程數(shù)、總耗時(shí)、單行代碼耗時(shí)、CPU執(zhí)行時(shí)間等信息。
在多行代碼分析的情況下的使用效果(分別統(tǒng)計(jì)生成一千萬長度、一億長度、兩億長度的列表耗時(shí)):
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 上加一個(gè)參數(shù) profile 就可以:
Pyinstrument還支持flask、異步代碼的性能分析,具體可以查看官方文檔進(jìn)行學(xué)習(xí)。
Pyinstrument也提供了豐富的api供我們使用,官網(wǎng)文檔有詳細(xì)的介紹:https://pyinstrument.readthedocs.io/en/latest/reference.html
根據(jù)官方文檔的描述來看,Pyinstrument的系統(tǒng)開銷會(huì)比cProfile 這類跟蹤分析器小很多,cProfile由于大量調(diào)用探查器,可能會(huì)扭曲測試結(jié)果:
關(guān)于“Python中怎么安裝和使用pyinstrument”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Python中怎么安裝和使用pyinstrument”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。