4个python内存性能检测工具:memory 您所在的位置:网站首页 查看内存消耗 4个python内存性能检测工具:memory

4个python内存性能检测工具:memory

2023-11-12 14:34| 来源: 网络整理| 查看: 265

这里总结了4个比较好的python性能检测工具,包括内存使用、运行时间、执行次数等方面。

1、memory_profiler查看内存的使用情况

memory_profiler可以用来测量python进程的内存使用情况。可以按行查看内存的使用情况。

memory_profiler 是一个监控进程内存消耗的模块,可以逐行分析 Python 程序的内存消耗。它是一个依赖 psutil 模块的纯 Python 模块。

只需要在目标函数上加个装饰器 @profile,就可以实现对此函数内存使用的统计。

安装:pip install -U memory_profiler

官方文档:https://pypi.org/project/memory-profiler/

案例1,脚本如下:

from memory_profiler import profile @profile def base_func1(): for n in range(10000): print(f'当前n的值是:{n}') base_func1() # 从返回的数据结果来看,执行当前函数使用了45.3 MiB的内存。返回结果如下: # 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))

案例2,脚本如下:

# -*- encoding: utf-8 -*- from memory_profiler import profile @profile def my_func(): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7) del b return a if __name__ == '__main__': my_func()

执行结果如下图: 在这里插入图片描述

2、timeit 时间使用情况

timeit是python的内置模块,可以测试单元格的代码运行时间,由于是内置模块所以并不需要单独安装。

import timeit def base_func2(): for n in range(10000): print(f'当前n的值是:{n}') res = timeit.timeit(base_func2,number=5) print(f'当前的函数的运行时间是:{res}') # 执行结果如下: # 0.09903816704172641 3、line_profiler行代码运行时间检测

官方文档:https://pypi.org/project/line-profiler/

安装:pip install line_profiler

from line_profiler import LineProfiler def base_func3(): for n in range(10000): print(f'当前n的值是:{n}') lp = LineProfiler() lp_wrap = lp(base_func3) lp_wrap() lp.print_stats() """ 执行结果如下:(单位时间为微妙) Line # Hits Time Per Hit % Time Line Contents ============================================================== 1 def base_func3(): 2 10000 1538000.0 153.8 2.8 for n in range(10000): 3 10000 53417000.0 5341.7 97.2 print('当前n的值是:{}'.format(n))""" 4、heartrate可视化检测工具

heartrate最值得推荐的是可以在网页上面向检测心率一样检测程序的执行过程,是非标准库,2019年11月停止更新。

文档:https://www.cnpython.com/pypi/heartrate

安装:pip install heartrate。

使用案例:

import heartrate heartrate.trace(browser=True) def base_func4(): for n in range(10000): print(f'当前n的值是:{n}')

执行完会在浏览器上显示: 在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有