memory_profiler

repository·master·Indexed 26 days ago

https://github.com/pythonprofilers/memory_profiler

A pure Python module for monitoring process memory consumption and performing line-by-line memory analysis. It features the @profile decorator for detailed function analysis, the mprof executable for time-based memory usage reports and plotting, and the memory_usage() API. It supports multiple backends including psutil, psutil_pss, psutil_uss, posix, and tracemalloc, and provides IPython magic commands like %mprun and %memit.

Tokens
2K
Snippets
12
Records
14
Agent score
39%

What's inside memory_profiler

  1. Perform line-by-line memory analysis

    master

    To analyze memory consumption line-by-line, decorate the target function with @profile. You can then run your script using the memory_profiler module via the Python interpreter. This will output a table showing line numbers, memory usage, increments, occurrences, and the code content.

    @profile
    def my_func():
        a = [1] * (10 ** 6)
        b = [2] * (2 * 10 ** 7)
        del b
        return a
    
    if __name__ == '__main__':
        my_func()

    Run the analysis

    $ python -m memory_profiler example.py
  2. Redirect output to the Python logger module using LogFile

    master

    To use the standard Python logging module (e.g., with RotatingFileHandler), redirect sys.stdout to a LogFile instance from the memory_profiler module.

    >>> from memory_profiler import LogFile
    >>> import sys
    >>> sys.stdout = LogFile('memory_profile_log')
  3. Track forked child processes with mprof

    master

    By default, mprof only tracks the parent process. To include child processes in a multiprocessing context, use one of the following:

    1. Sum child memory into parent: Use the --include-children flag.
    2. Track children independently: Use the --multiprocess flag to see individual rows for each child in the plot.
    # Sum children memory with parent
    mprof run --include-children <script>
    
    # Track each child independently
    mprof run --multiprocess <script>
    mprof plot
  4. Use memory_profiler IPython magics

    master

    If using IPython, you can use the following magic commands for profiling:

    • %mprun / %%mprun: Provides a line-by-line memory report. Note that the function must be defined in a file, not interactively. Use the -f parameter to specify the function.
    • %memit / %%memit: Measures peak memory and increment for a specific statement or cell (analogous to %timeit).

    To enable these, load the extension using %load_ext memory_profiler or add 'memory_profiler' to your c.InteractiveShellApp.extensions in your IPython configuration file.

    # Line-by-line profiling in IPython
    In [2]: %mprun -f my_func my_func()
    
    # Cell mode line-by-line profiling
    In [3]: %%mprun -f my_func -f my_func_2
           ...: my_func()
           ...: my_func_2()
    
    # Measuring memory for a single statement
    In [1]: %memit range(10000)
    
    # Cell mode memory measurement
    In [3]: %%memit l=range(1000000)
           ...: len(l)
  5. Redirect memory profile output to a log file

    master

    You can redirect the output of the @profile decorator to a specific IO stream by passing the stream parameter. This is useful for writing profiling results directly to a file.

    >>> 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
  6. Customize reporting with LogFile

    master

    When using LogFile, you can control the verbosity of the output. For example, set reportIncrementFlag=False to exclude entries that only show memory increments, focusing instead on total usage.

    >>> from memory_profiler import LogFile
    >>> import sys
    >>> sys.stdout = LogFile('memory_profile_log', reportIncrementFlag=False)
  7. Use the @profile decorator

    master

    You can use the profile decorator directly in your code to enable line-by-line profiling without needing the -m memory_profiler command-line flag. You can also specify the decimal precision for the output.

    from memory_profiler import profile
    
    @profile(precision=4)
    def my_func():
        a = [1] * (10 ** 6)
        b = [2] * (2 * 10 ** 7)
        del b
        return a
  8. memory_usage() API

    master

    The memory_usage function returns the memory usage over a specified time interval.

    Arguments:

    • proc: The process to monitor. Can be a PID (use -1 for the current process), a string of Python code, or a tuple (f, args, kw) representing a function f to be executed with *args and **kw.
    from memory_profiler import memory_usage
    
    # Monitor current process for 1s with 0.2s intervals
    mem_usage = memory_usage(-1, interval=.2, timeout=1)
    
    # Monitor a specific function execution
    def f(a, n=100):
        import time
        time.sleep(2)
        b = [a] * n
        time.sleep(1)
        return b
    
    usage = memory_usage((f, (1,), {'n' : int(1e6)}))
  9. mprof CLI commands reference

    master

    The following commands are available for the mprof utility:

    • mprof run: Run an executable and record memory usage.
    • mprof plot: Plot recorded memory usage (defaults to the last recording).
    • mprof list: List all recorded memory usage files.
    • mprof clean: Remove all recorded memory usage files.
    • mprof rm: Remove specific recorded memory usage files.
  10. Configure memory tracking backends

    master

    The profiler supports several backends for measuring memory:

    • psutil (Default): Measures RSS (Resident Set Size).
    • psutil_pss: Measures PSS (Proportional Set Size).
    • psutil_uss: Measures USS (Unique Set Size).
    • posix
    • tracemalloc

    You can specify the backend via the CLI or the memory_usage API.

    # Via CLI
    $ python -m memory_profiler --backend psutil my_script.py
    # Via API
    from memory_profiler import memory_usage
    mem_usage = memory_usage(-1, interval=.2, timeout=1, backend="psutil")