python性能检测怎样做,有哪些工具
Admin 2022-08-30 群英技术资讯 743 次浏览
这篇文章主要讲解了“python性能检测怎样做,有哪些工具”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“python性能检测怎样做,有哪些工具”吧!这里总结了五个比较好的python性能检测工具,包括内存使用、运行时间、执行次数等方面。
首先,来编写一个基础的python函数用于在后面的各种性能测试。
def base_func():
for n in range(10000):
print('当前n的值是:{}'.format(n))
memory_profiler是python的非标准库,所以这里采用pip的方式进行安装。它能够监视进程、了解内存使用等情况。
pip install memory_profiler
安装好memory_profiler库以后,直接使用注解的方式进行测试。
from memory_profiler import profile
@profile
def base_func1():
for n in range(10000):
print('当前n的值是:{}'.format(n))
base_func1()
# Line # Mem usage Increment Occurrences Line Contents
# =============================================================
# 28 45.3 MiB 45.3 MiB 1 @profile
# 29 def base_func():
# 30 45.3 MiB 0.0 MiB 10001 for n in range(10000):
# 31 45.3 MiB 0.0 MiB 10000 print('当前n的值是:{}'.format(n))
从返回的数据结果来看,执行当前函数使用了45.3 MiB的内存。
timeit是python的内置模块,可以测试单元格的代码运行时间,由于是内置模块所以并不需要单独安装。
import timeit
def base_func2():
for n in range(10000):
print('当前n的值是:{}'.format(n))
res = timeit.timeit(base_func2,number=5)
print('当前的函数的运行时间是:{}'.format(res))
# 当前的函数的运行时间是:0.9675800999999993
根据上面函数的运行返回结果,函数的运行时间是0.96秒。
如果在只需要检测函数的局部运行时间的话就可以使用line_profiler了,它可以检测出每行代码的运行时间。
line_profiler是python的非标准库,使用的使用pip的方式安装一下。
pip install line_profiler
最简便的使用方式直接将需要测试的函数加入即可。
def base_func3():
for n in range(10000):
print('当前n的值是:{}'.format(n))
from line_profiler import LineProfiler
lp = LineProfiler()
lp_wrap = lp(base_func3)
lp_wrap()
lp.print_stats()
# Line # Hits Time Per Hit % Time Line Contents
# ==============================================================
# 72 def base_func3():
# 73 10001 162738.0 16.3 4.8 for n in range(10000):
# 74 10000 3207772.0 320.8 95.2 print('当前n的值是:{}'.format(n))
从运行结果可以看出每行代码的运行时间及比例,注意这里的时间单位是微妙。
heartrate最值得推荐的是可以在网页上面向检测心率一样检测程序的执行过程,同时,他还是非标准库,使用pip的方式进行安装。
pip install heartrate
import heartrate
heartrate.trace(browser=True)
def base_func4():
for n in range(10000):
print('当前n的值是:{}'.format(n))
运行以后,控制台打印如下日志:
# * Serving Flask app "heartrate.core" (lazy loading) # * Environment: production # WARNING: This is a development server. Do not use it in a production deployment. # Use a production WSGI server instead. # * Debug mode: off
并且自动打开浏览器地址:http://127.0.0.1:9999

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
Python内置函数-eval() 函数。 eval() 函数用来执行一个字符串表达式,并返回表达式的值。
动机从一个问题引出 MetaClassMetaclass 编程动机python语言因为工作偏向于 AI ,所以对于这门语言还停留在表面,对于 python 深层并没有接触到。今天来聊一聊元类(metacla
今天我们先讲一下编写python脚本处理json的核心功能,有些散乱,后期在进行整体脚本的编写,对python json字典关系相关知识感兴趣的朋友一起看看吧
这篇文章主要为大家介绍了Python实现两种多分类混淆矩阵,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
这篇文章主要介绍了解决pytorch rnn 变长输入序列的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008