programing tip

어떤 Python 메모리 프로파일 러가 권장됩니까?

itbloger 2020. 10. 2. 21:46
반응형

어떤 Python 메모리 프로파일 러가 권장됩니까? [닫은]


내 Python 애플리케이션의 메모리 사용량을 알고 싶고 특히 어떤 코드 블록 / 부분 또는 객체가 대부분의 메모리를 소비하는지 알고 싶습니다. Google 검색에 따르면 상용 제품은 Python Memory Validator (Windows 전용)입니다.

오픈 소스는 PySizerHeapy 입니다.

나는 아무도 시도하지 않았으므로 어떤 것이 가장 좋은지 알고 싶었습니다.

  1. 대부분의 세부 정보를 제공합니다.

  2. 내 코드를 최소한 또는 전혀 변경해야합니다.


Heapy 는 사용하기 매우 간단합니다. 코드의 어느 시점에서 다음을 작성해야합니다.

from guppy import hpy
h = hpy()
print h.heap()

이것은 다음과 같은 출력을 제공합니다.

Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
0  35144  27  2140412  26   2140412  26 str
1  38397  29  1309020  16   3449432  42 tuple
2    530   0   739856   9   4189288  50 dict (no owner)

객체가 참조되는 위치를 찾아서 그에 대한 통계를 얻을 수도 있지만, 그에 대한 문서는 약간 희박합니다.

Tk로 작성된 그래픽 브라우저도 있습니다.


아무도 그것을 언급하지 않았기 때문에 메모리 사용량에 대한 줄 단위 보고서를 인쇄 할 수 있고 Unix 및 Windows에서 작동 하는 내 모듈 memory_profiler 를 가리킬 것입니다 (이 마지막 항목에서는 psutil이 필요함). 출력은 그다지 상세하지 않지만, 목표는 할당 된 객체에 대한 철저한 분석이 아니라 코드가 더 많은 메모리를 소비하는 위치에 대한 개요를 제공하는 것입니다.

함수를 장식 @profile하고 -m memory_profiler플래그를 사용 하여 코드를 실행 하면 다음과 같은 줄 단위 보고서가 인쇄됩니다.

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

나는 Dowser를 추천 합니다. 설정이 매우 쉽고 코드를 변경할 필요가 없습니다. 간단한 웹 인터페이스에서 시간에 따른 각 유형의 개체 수, 라이브 개체 목록보기, 라이브 개체에 대한 참조보기 등을 모두 볼 수 있습니다.

# memdebug.py

import cherrypy
import dowser

def start(port):
    cherrypy.tree.mount(dowser.Root())
    cherrypy.config.update({
        'environment': 'embedded',
        'server.socket_port': port
    })
    cherrypy.server.quickstart()
    cherrypy.engine.start(blocking=False)

memdebug를 가져오고 memdebug.start를 호출합니다. 그게 다야.

PySizer 또는 Heapy를 사용해 보지 않았습니다. 다른 사람들의 리뷰에 감사드립니다.

최신 정보

위의 코드입니다 CherryPy 2.X, 방법은 제거하고 하지 않습니다 플래그. 따라서 사용하는 경우CherryPy 3.Xserver.quickstartengine.startblockingCherryPy 3.X

# memdebug.py

import cherrypy
import dowser

def start(port):
    cherrypy.tree.mount(dowser.Root())
    cherrypy.config.update({
        'environment': 'embedded',
        'server.socket_port': port
    })
    cherrypy.engine.start()

objgraph 라이브러리를 고려 하십시오 (예제 사용 사례는 http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks ).


Muppy is (yet another) Memory Usage Profiler for Python. The focus of this toolset is laid on the identification of memory leaks.

Muppy tries to help developers to identity memory leaks of Python applications. It enables the tracking of memory usage during runtime and the identification of objects which are leaking. Additionally, tools are provided which allow to locate the source of not released objects.


I found meliae to be much more functional than Heapy or PySizer. If you happen to be running a wsgi webapp, then Dozer is a nice middleware wrapper of Dowser


I'm developing a memory profiler for Python called memprof:

http://jmdana.github.io/memprof/

It allows you to log and plot the memory usage of your variables during the execution of the decorated methods. You just have to import the library using:

from memprof import memprof

And decorate your method using:

@memprof

This is an example on how the plots look like:

enter image description here

The project is hosted in GitHub:

https://github.com/jmdana/memprof


Try also the pytracemalloc project which provides the memory usage per Python line number.

EDIT (2014/04): It now has a Qt GUI to analyze snapshots.

참고URL : https://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended

반응형