日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python中性能分析利器pyinstrument詳細(xì)講解_python

作者:曲鳥 ? 更新時間: 2022-04-11 編程語言

一、前言

程序的性能也是非常關(guān)鍵的指標(biāo),很多時候你的代碼跑的快,更能夠體現(xiàn)你的技術(shù)。最近發(fā)現(xià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í)行時間,生成可視化的報告等更完善的性能分析時就有點力不從心了。這個時候可以使用python的第三方庫Pyinstrument來進(jìn)行性能分析。

二、Pyinstrument使用

Pyinstrument 是一個 Python 分析器。分析器是一種幫助您優(yōu)化代碼的工具 - 使其更快。要獲得最大的速度提升。
Pyinstrument 官方文檔:pyinstrument

Pyinstrument 安裝:

pip install pyinstrument

1. 舉例

對于最開始我們舉的例子,使用Pyinstrument實現(xiàn)的代碼如下:

文末添加個人VX,獲取資料和免費答疑

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.pyMIDDLEWARE 中添加如下配置:

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é)

原文鏈接:https://blog.csdn.net/momoda118/article/details/122805206

欄目分類
最近更新