记录memory_profiler的报表

4 投票
3 回答
8517 浏览
提问于 2025-04-18 09:17

我正在使用 memory_profiler 来分析我的代码。

from memory_profiler import profile

@profile
def whatever():
    ....
    ....

所以,大家可能知道,我在屏幕上看到的输出大概是这样的:

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

我的问题是:

因为 @profile 这个过程需要花费很多时间,我在想有没有办法把这个输出记录下来,顺便让脚本继续运行,也许可以在晚上运行。

我的想法是,在很多函数前面加上 @profile 装饰器,然后把所有的结果以某种方式存储在一个 TXT 文件里,或者多个不同的 TXT 文件里,这个不太重要,重要的是这样做是否可行。

3 个回答

0

要把 memory_profiler 的输出结果发送到日志文件,最好的例子可以在它的代码库里找到:

https://github.com/pythonprofilers/memory_profiler/blob/master/examples/reporting_logger.py

5

我还没试过,但看起来很简单 - 从文档中可以看到:

报告

你可以通过给装饰器传递一个输入输出流(IO流)作为参数,来把输出重定向到一个日志文件,比如用 @profile(stream=fp)。

>>> fp=open('memory_profiler.log','w+')
>>> @profile(stream=fp)
>>> def my_func():
    ...     a = [1] * (10 ** 6)
    ...     b = [2] * (2 * 10 ** 7)
    ...     del b
    ...     return a

如果你有很多文本或日志文件,比如想把不同函数或代码块的结果分别保存,可以在装饰函数时传递不同的文件对象:

fp=open('memory_profiler.log','w+')
@profile(stream=fp)
def func1():
    # statements

fp2=open('memory_profiler2.log', 'w+')
@profile(stream=fp2)
def func2():
    # statements
.....

缺点是:会有很多打开的连接。


想要优雅地记录到多个文件,可以使用RotatingFileHandler

有时候使用日志模块会非常方便,特别是当我们需要使用RotatingFileHandler的时候。只需利用内存分析器模块的LogFile,就可以把输出重定向到日志模块。

.

from memory_profiler import LogFile
import sys

sys.stdout = LogFile('memory_profile_log')
7

根据评论的内容:

如果你在命令行中直接运行

run_my_thing > output.txt

这样可以把 stdout 的内容保存到一个文件里。

这样做可以绕过内存分析工具。显然,单纯地重定向 stdout 并不是最理想的办法,但如果只是为了人来分析,这样做应该问题不大。

撰写回答