Python 内存分析器 Memory Profiler

码农软件 · 软件分类 · 性能测试和优化 · 2019-11-26 22:14:15

软件介绍

Memory Profiler 是一个 python 模块,用于监视进程的内存消耗,甚至可以逐行分析 python 程序的内存消耗。 它是一个纯 python 模块,并有 psutil 模块作为可选(但强烈推荐)依赖。

Usage

line-by-line 内存使用模式与 line_profiler 的使用方式非常相似:首先用 @profile 修饰你需要监视的函数,然后使用特殊脚本运行脚本。

在下面的示例中,我们创建一个简单的函数 my_func,它分配列表a、b,然后删除 b:

@profile
def my_func():
    a = [1] * (10 ** 6)
    b = [2] * (2 * 10 ** 7)
    del b
    return a

if __name__ == '__main__':
    my_func()

执行将选项 -m memory_profiler 传递给 python 解释器的代码,以加载 memory_profiler 模块并打印到 stdout 进行逐行分析。 如果文件名是 example.py,这将导致:

$ python -m memory_profiler example.py

输出如下:

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

第一列表示已经概要分析的代码的行号,第二列(Mem用法)表示 Python 解释器在执行该行之后的内存使用情况。 第三列(增量)表示当前行相对于最后一行的存储器的差异。 最后一列打印已分析的代码。

本文地址:https://codercto.com/soft/d/19869.html

Learn Python the Hard Way

Learn Python the Hard Way

Zed Shaw / Example Product Manufacturer / 2011

This is a very beginner book for people who want to learn to code. If you can already code then the book will probably drive you insane. It's intended for people who have no coding chops to build up t......一起来看看 《Learn Python the Hard Way》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具