Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从memory_profiler记录报告_Python_Profiler_Memory Profiling - Fatal编程技术网

Python 从memory_profiler记录报告

Python 从memory_profiler记录报告,python,profiler,memory-profiling,Python,Profiler,Memory Profiling,我正在使用内存分析器分析我的代码 from memory_profiler import profile @profile def whatever(): .... .... 所以,正如你们中的许多人可能知道的,我在屏幕上得到类似的输出: Line # Mem usage Increment Line Contents ============================================== 3

我正在使用内存分析器分析我的代码

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函数中使用decorator@profile,并以某种方式将所有结果存储在一个TXT或多个不同的TXT文件中,这并不重要,重要的是如果可能的话。

从注释中可以看出:

如果你只是跑

run_my_thing > output.txt
在shell中,您可以将
stdout
存储在文件中


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

我没有尝试过,但看起来很简单-从以下方面:

报告

通过将IO流传递为,可以将输出重定向到日志文件 类似@profile(stream=fp)的装饰器的参数


对于许多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时。 只需使用 内存探查器模块的日志文件


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


你可以使用,你就不能直接用管道传递结果吗?这是一个又快又脏的解决方案。@Veedrac,对不起,我不太懂你的意思,我不太喜欢
内存剖析器
,我只知道如何让它工作,但我甚至不知道输出来自哪里。这将有助于我的思考。只需在shell中运行我的东西output.txt即可。完全绕过
memory\u profiler
。很明显,这并不理想。谢谢Veedrac,我其实不在乎它有多理想,如果它能工作,那么对我来说就足够了,谢谢。
fp=open('memory_profiler.log','w+')
@profile(stream=fp)
def func1():
    # statements

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

sys.stdout = LogFile('memory_profile_log')