memory_profiler初体验

2020年11月6日 / 613次阅读 / Last Modified 2020年11月6日

memory_profiler是一个第三方模块,用来测量python进程的内存使用情况。

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

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

$ cat read2.py
import mmap
import os
from functools import partial


def read_file(filename, block_size=mmap.PAGESIZE*1024*256):
    filesize = os.path.getsize(filename)
    with open(filename, 'rb+') as f:
        i = 0
        readlen = 0
        while True:
            length = block_size if filesize-readlen>block_size else filesize-readlen
            mm = mmap.mmap(f.fileno(), length, offset=readlen)
            cont = mm.read()
            mm.close()
            yield cont
            readlen += len(cont)
            if readlen == filesize:
                break
            i += 1


@profile
def do():
    length = 0
    for cont in read_file('bigfile'):
        length += len(cont)

    print(length)


do()

这是一个尝试用mmap来读取大文件的测试,bigfile有1.6G。(这个测试是失败的,使用mmap并没有提高读取超大文件的速度,也没有使用更少的内存,直接使用文件对象的read(N)反而更快更好)

$ python3 -m memory_profiler read2.py
1677721600
Filename: read2.py

Line #    Mem usage    Increment  Occurences   Line Contents
============================================================
    23   18.426 MiB   18.426 MiB           1   @profile
    24                                         def do():
    25   18.426 MiB    0.000 MiB           1       length = 0
    26 1042.613 MiB  128.188 MiB           3       for cont in read_file('bigfile'):
    27 1042.613 MiB -448.000 MiB           2           length += len(cont)
    28
    29  594.613 MiB -448.000 MiB           1       print(length)

如果代码执行时间很短,用top等其它工具不一定能够捕获到其内存的情况,用memory_profiler模块就很方便了。

用完后,记得删除 @profile 装饰器!

memory_profiler 还有其它的功能,以后再总结。

-- EOF --

本文链接:https://www.pynote.net/archives/2753

相关文章

    留言区

    《memory_profiler初体验》有3条留言

    您的电子邮箱地址不会被公开。 必填项已用*标注

    • 麦新杰

      注意两个细节:(1)用memory_profiler启动py文件,不需要chmod +x;(2)注意这个--include-children参数:

      $ python3 -m memory_profiler -h
      usage: python -m memory_profiler script_file.py
      
      positional arguments:
        program               python script or module followed by command line arguements to run
      
      optional arguments:
        -h, --help            show this help message and exit
        --version             show program's version number and exit
        --pdb-mmem MAXMEM     step into the debugger when memory exceeds MAXMEM
        --precision PRECISION
                              precision of memory output in number of significant digits
        -o OUT_FILENAME       path to a file where results will be written
        --timestamp           print timestamp instead of memory measurement for decorated functions
        --include-children    also include memory used by child processes
        --backend {tracemalloc,psutil,posix}
                              backend using for getting memory info (one of the {tracemalloc, psutil, posix})
      
       [回复]

    • 麦新杰

      这次初次使用memory_profiler模块,发现对于generator是不支持的。 [回复]

    • 麦新杰

      安装memory_profiler:

      $ python3 -m pip install --user memory_profiler
       [回复]


    前一篇:
    后一篇:

    More

    麦新杰的Python笔记

    Ctrl+D 收藏本页


    ©Copyright 麦新杰 Since 2019 Python笔记

    go to top