簡體   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