记录memory_profiler中的报告

cod*_*ler 3 python profiler memory-profiling

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

from memory_profiler import profile

@profile
def whatever():
    ....
    ....
Run Code Online (Sandbox Code Playgroud)

所以,正如你们许多人可能知道我在屏幕上得到类似这样的输出:

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
Run Code Online (Sandbox Code Playgroud)

我的问题是:

由于@profile进程需要花费很多时间,因此我想知道我是否可以以某种方式记录/存储此输出,并让脚本保持运行,可能是在晚上.

我的想法是在许多def函数中使用装饰器@profile,并将所有结果以某种方式存储在单个TXT或许多不同的TXT文件中,这不是重要的,重要的是如果可能的话.

Vee*_*rac 6

从评论中可以看出:

如果你只是跑

run_my_thing > output.txt
Run Code Online (Sandbox Code Playgroud)

在shell中,您可以存储stdout在文件中.

这将完全绕过memory_profiler.显然,仅重定向并不理想stdout,但如果是人工分析则不应该是一个大问题.


Nab*_*med 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
Run Code Online (Sandbox Code Playgroud)

对于许多 txt/日志文件,即分别保存各种函数/代码块的结果 - 在装饰函数时传递不同的文件对象:

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

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

缺点:大量开放连接。


记录到多个文件的优雅方法是使用RotatingFileHandler

有时,特别是当我们需要使用RotatingFileHandler时,使用logger模块会非常方便。只需利用内存分析器模块的日志文件即可将输出重定向到记录器模块

from memory_profiler import LogFile
import sys

sys.stdout = LogFile('memory_profile_log')
Run Code Online (Sandbox Code Playgroud)