繁体   English   中英

从 memory_profiler 记录报告

[英]log a report from memory_profiler

我正在使用 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 过程需要很多时间,我想知道是否可以以某种方式记录/存储此输出,并让脚本运行,也许在夜间。

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

从评论来看:

如果你只是跑

run_my_thing > output.txt

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

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

我还没有尝试过,但看起来很简单 - 从文档中

报告

通过将 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

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

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 时,使用 logger 模块会非常方便。 只需使用内存分析器模块的 LogFile 即可将输出重定向到记录器模块

.

from memory_profiler import LogFile
import sys

sys.stdout = LogFile('memory_profile_log')

memory_profiler输出发送到日志文件的最佳示例可以在其 repo 中找到:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM