php中文网 | cnphp.com

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 659|回复: 0

Python性能分析利器pyinstrument讲解

[复制链接]

2871

主题

2881

帖子

1万

积分

管理员

Rank: 9Rank: 9Rank: 9

UID
1
威望
0
积分
7283
贡献
0
注册时间
2021-4-14
最后登录
2024-9-19
在线时间
715 小时
QQ
发表于 2022-2-12 22:10:08 | 显示全部楼层 |阅读模式
一、前言
程序的性能也是非常关键的指标,很多时候你的代码跑的快,更能够体现你的技术。最近发现很多小伙伴在性能分析的过程中都是手动打印运行时间的方式来统计代码耗时的:
[mw_shl_code=applescript,true]import datetime
start=datetime.datetime.now()
b=[i for i in range(10000000)]  # 生成长度为一千万的列表
end=datetime.datetime.now()
print(end-start)
[/mw_shl_code]
输出结果
[mw_shl_code=applescript,true]0:00:00.377766
[/mw_shl_code]
这种方法使用很快捷,但需要统计每行代码的执行时间,生成可视化的报告等更完善的性能分析时就有点力不从心了。这个时候可以使用python的第三方库Pyinstrument来进行性能分析。
二、Pyinstrument使用
Pyinstrument 是一个 Python 分析器。分析器是一种帮助您优化代码的工具 - 使其更快。要获得最大的速度提升。
Pyinstrument 官方文档:pyinstrument

Pyinstrument 安装:

pip install pyinstrument

1. 举例
对于最开始我们举的例子,使用Pyinstrument实现的代码如下:
[mw_shl_code=applescript,true]文末添加个人VX,获取资料和免费答疑

from pyinstrument import Profiler
profiler=Profiler()
profiler.start()
b=[i for i in range(10000000)]# 生成长度为一千万的列表
profiler.stop()
profiler.print()
[/mw_shl_code]
输出结果
[mw_shl_code=applescript,true]  _     ._   __/__   _ _  _  _ _/_   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 #单行代码耗时
[/mw_shl_code]
打印的信息包含了记录时间、线程数、总耗时、单行代码耗时、CPU执行时间等信息。

在多行代码分析的情况下的使用效果(分别统计生成一千万长度、一亿长度、两亿长度的列表耗时):
[mw_shl_code=applescript,true]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()
[/mw_shl_code]
输出结果
[mw_shl_code=applescript,true]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
[/mw_shl_code]
2. Pyinstrument分析django代码
使用Pyinstrument分析 Django 代码非常简单,只需要在 Django 的配置文件settings.py的 MIDDLEWARE 中添加如下配置:
[mw_shl_code=applescript,true]MIDDLEWARE = [
        ...
    'pyinstrument.middleware.ProfilerMiddleware',
        ...
]
[/mw_shl_code]
然后就可以在 url 上加一个参数 profile 就可以:
image.png
Pyinstrument还支持flask、异步代码的性能分析,具体可以查看官方文档进行学习。
Pyinstrument也提供了丰富的api供我们使用,官网文档有详细的介绍:https://pyinstrument.readthedocs.io/en/latest/reference.html

三、Pyinstrument与cProfile(python自带性能分析器)的不同
根据官方文档的描述来看,Pyinstrument的系统开销会比cProfile 这类跟踪分析器小很多,cProfile由于大量调用探查器,可能会扭曲测试结果:
image.png

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|php中文网 | cnphp.com ( 赣ICP备2021002321号-2 )

GMT+8, 2024-9-20 06:04 , Processed in 0.184204 second(s), 34 queries , Gzip On.

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2020, Tencent Cloud.

申明:本站所有资源皆搜集自网络,相关版权归版权持有人所有,如有侵权,请电邮(fiorkn@foxmail.com)告之,本站会尽快删除。

快速回复 返回顶部 返回列表