Python性能分析利器pyinstrument讲解

简介: Python性能分析利器pyinstrument讲解

一、前言


程序的性能也是非常关键的指标,很多时候你的代码跑的快,更能够体现你的技术。最近发现很多小伙伴在性能分析的过程中都是手动打印运行时间的方式来统计代码耗时的:


import datetime
start=datetime.datetime.now()
b=[i for i in range(10000000)]  # 生成长度为一千万的列表
end=datetime.datetime.now()
print(end-start)


输出结果


0:00:00.377766


这种方法使用很快捷,但需要统计每行代码的执行时间,生成可视化的报告等更完善的性能分析时就有点力不从心了。这个时候可以使用python的第三方库Pyinstrument来进行性能分析。


二、Pyinstrument使用


Pyinstrument 是一个 Python 分析器。分析器是一种帮助您优化代码的工具 - 使其更快。要获得最大的速度提升。

Pyinstrument 官方文档:pyinstrument


Pyinstrument 安装:


pip install pyinstrument


1. 举例


对于最开始我们举的例子,使用Pyinstrument实现的代码如下:

文末添加个人VX,获取资料和免费答疑
from pyinstrument import Profiler
profiler=Profiler()
profiler.start()
b=[i for i in range(10000000)]# 生成长度为一千万的列表
profiler.stop()
profiler.print()

输出结果

  _     ._   __/__   _ _  _  _ _/_   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  #执行总耗时
└─ 0.385 <listcomp>  test2.py:7 #单行代码耗时

打印的信息包含了记录时间、线程数、总耗时、单行代码耗时、CPU执行时间等信息。


在多行代码分析的情况下的使用效果(分别统计生成一千万长度、一亿长度、两亿长度的列表耗时):

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

输出结果


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 上加一个参数 profile 就可以:


9e8d85560fab41e3b00f207c85fcc4d9.png

Pyinstrument还支持flask、异步代码的性能分析,具体可以查看官方文档进行学习。

Pyinstrument也提供了丰富的api供我们使用,官网文档有详细的介绍:https://pyinstrument.readthedocs.io/en/latest/reference.html


三、Pyinstrument与cProfile(python自带性能分析器)的不同


根据官方文档的描述来看,Pyinstrument的系统开销会比cProfile 这类跟踪分析器小很多,cProfile由于大量调用探查器,可能会扭曲测试结果:


0f7fd7520e274265aa640511495949c6.png

目录
相关文章
|
6月前
|
Python
170 python - 内置类型性能分析
170 python - 内置类型性能分析
26 0
|
算法 Python
python散列表实现查找,使用了多种算法并测试对比进行了性能分析(查找效率)
散列表实现查找 本章是填补之前文章的坑,对哈希算法进行了实现,使用了平方取中法/除留余数法进行哈希映射,使用开放地址与公共溢出区解决冲突,同时对不同方法进行了性能分析对比,最后进行了总结。 可以转载,但请声明源链接:文章源链接justin3go.com(有些latex公式某些平台不能渲染可查看这个网站)
100 0
|
Python
Python日学壹技:性能分析
Python日学壹技:性能分析
58 0
|
Java Go Python
python 性能分析利器 py-spy
python 内存泄漏工具以及性能瓶颈分析工具分享。
4499 0
|
UED Python
如何进行 Python性能分析,你才能如鱼得水?
本文作者为 Bryan Helmig,主要介绍 Python 应用性能分析的三种进阶方案。文章系国内 ITOM 管理平台 OneAPM 编译呈现。
1549 0
|
18小时前
|
数据采集 算法 Python
2024年Python最全python基础入门:高阶函数,小米面试编程题
2024年Python最全python基础入门:高阶函数,小米面试编程题