memory-profiler


Namememory-profiler JSON
Version 0.61.0 PyPI version JSON
download
home_pagehttps://github.com/pythonprofilers/memory_profiler
SummaryA module for monitoring memory usage of a python program
upload_time2022-11-15 17:57:28
maintainer
docs_urlNone
authorFabian Pedregosa
requires_python>=3.5
licenseBSD
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            .. image:: https://travis-ci.org/pythonprofilers/memory_profiler.svg?branch=master
    :target: https://travis-ci.org/pythonprofilers/memory_profiler

=================
 Memory Profiler
=================


**Note:** This package is no longer actively maintained. I won't be actively responding to issues. If you'd like to volunteer to maintain it, please drop me a line at f@bianp.net

This is a python module for monitoring memory consumption of a process
as well as line-by-line analysis of memory consumption for python
programs. It is a pure python module which depends on the `psutil
<http://pypi.python.org/pypi/psutil>`_ module.


==============
 Installation
==============
Install via pip::

    $ pip install -U memory_profiler

The package is also available on `conda-forge
<https://github.com/conda-forge/memory_profiler-feedstock>`_.

To install from source, download the package, extract and type::

    $ pip install .

===========
Quick Start
===========

Use `mprof` to generate a full memory usage report of your executable and to plot it.

.. code-block:: bash

    mprof run executable
    mprof plot

The plot would be something like this:

.. image:: https://i.stack.imgur.com/ixCH4.png

=======
 Usage
=======


line-by-line memory usage
=========================

The line-by-line memory usage mode is used much in the same way of the
`line_profiler <https://pypi.python.org/pypi/line_profiler/>`_: first
decorate the function you would like to profile with ``@profile`` and
then run the script with a special script (in this case with specific
arguments to the Python interpreter).

In the following example, we create a simple function ``my_func`` that
allocates lists ``a``, ``b`` and then deletes ``b``::


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

    if __name__ == '__main__':
        my_func()


Execute the code passing the option ``-m memory_profiler`` to the
python interpreter to load the memory_profiler module and print to
stdout the line-by-line analysis. If the file name was example.py,
this would result in::

    $ python -m memory_profiler example.py

Output will follow::

    Line #    Mem usage    Increment  Occurrences   Line Contents
    ============================================================
         3   38.816 MiB   38.816 MiB           1   @profile
         4                                         def my_func():
         5   46.492 MiB    7.676 MiB           1       a = [1] * (10 ** 6)
         6  199.117 MiB  152.625 MiB           1       b = [2] * (2 * 10 ** 7)
         7   46.629 MiB -152.488 MiB           1       del b
         8   46.629 MiB    0.000 MiB           1       return a


The first column represents the line number of the code that has been
profiled, the second column (*Mem usage*) the memory usage of the
Python interpreter after that line has been executed. The third column
(*Increment*) represents the difference in memory of the current line
with respect to the last one. The last column (*Line Contents*) prints
the code that has been profiled.

Decorator
=========
A function decorator is also available.  Use as follows::

    from memory_profiler import profile

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

In this case the script can be run without specifying ``-m
memory_profiler`` in the command line.

In function decorator, you can specify the precision as an argument to the
decorator function.  Use as follows::

    from memory_profiler import profile

    @profile(precision=4)
    def my_func():
        a = [1] * (10 ** 6)
        b = [2] * (2 * 10 ** 7)
        del b
        return a

If a python script with decorator ``@profile`` is called using ``-m
memory_profiler`` in the command line, the ``precision`` parameter is ignored.

Time-based memory usage
==========================
Sometimes it is useful to have full memory usage reports as a function of
time (not line-by-line) of external processes (be it Python scripts or not).
In this case the executable ``mprof`` might be useful. Use it like::

    mprof run <executable>
    mprof plot

The first line run the executable and record memory usage along time,
in a file written in the current directory.
Once it's done, a graph plot can be obtained using the second line.
The recorded file contains a timestamps, that allows for several
profiles to be kept at the same time.

Help on each `mprof` subcommand can be obtained with the `-h` flag,
e.g. `mprof run -h`.

In the case of a Python script, using the previous command does not
give you any information on which function is executed at a given
time. Depending on the case, it can be difficult to identify the part
of the code that is causing the highest memory usage.

Adding the `profile` decorator to a function(ensure no 
`from memory_profiler import profile` statement) and running the Python
script with

    mprof run --python python <script>

will record timestamps when entering/leaving the profiled function. Running

    mprof plot

afterward will plot the result, making plots (using matplotlib) similar to these:

.. image:: https://camo.githubusercontent.com/3a584c7cfbae38c9220a755aa21b5ef926c1031d/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313930383631382f3836313332302f63623865376337382d663563632d313165322d386531652d3539373237623636663462322e706e67
   :target: https://github.com/scikit-learn/scikit-learn/pull/2248
   :height: 350px

or, with ``mprof plot --flame`` (the function and timestamp names will appear on hover):

.. image:: ./images/flamegraph.png
   :height: 350px

A discussion of these capabilities can be found `here <http://fa.bianp.net/blog/2014/plot-memory-usage-as-a-function-of-time/>`_.

.. warning:: If your Python file imports the memory profiler `from memory_profiler import profile` these timestamps will not be recorded. Comment out the import, leave your functions decorated, and re-run.

The available commands for `mprof` are:

  - ``mprof run``: running an executable, recording memory usage
  - ``mprof plot``: plotting one the recorded memory usage (by default,
    the last one)
  - ``mprof list``: listing all recorded memory usage files in a
    user-friendly way.
  - ``mprof clean``: removing all recorded memory usage files.
  - ``mprof rm``: removing specific recorded memory usage files

Tracking forked child processes
===============================
In a multiprocessing context the main process will spawn child processes whose
system resources are allocated separately from the parent process. This can
lead to an inaccurate report of memory usage since by default only the parent
process is being tracked. The ``mprof`` utility provides two mechanisms to
track the usage of child processes: sum the memory of all children to the
parent's usage and track each child individual.

To create a report that combines memory usage of all the children and the
parent, use the ``include-children`` flag in either the ``profile`` decorator or
as a command line argument to ``mprof``::

    mprof run --include-children <script>

The second method tracks each child independently of the main process,
serializing child rows by index to the output stream. Use the ``multiprocess``
flag and plot as follows::

    mprof run --multiprocess <script>
    mprof plot

This will create a plot using matplotlib similar to this:

.. image:: https://cloud.githubusercontent.com/assets/745966/24075879/2e85b43a-0bfa-11e7-8dfe-654320dbd2ce.png
    :target: https://github.com/pythonprofilers/memory_profiler/pull/134
    :height: 350px

You can combine both the ``include-children`` and ``multiprocess`` flags to show
the total memory of the program as well as each child individually. If using
the API directly, note that the return from ``memory_usage`` will include the
child memory in a nested list along with the main process memory.

Plot settings
===============================

By default, the command line call is set as the graph title. If you wish to customize it, you can use the ``-t`` option to manually set the figure title.


    mprof plot -t 'Recorded memory usage'

You can also hide the function timestamps using the ``n`` flag, such as

    mprof plot -n

Trend lines and its numeric slope can be plotted using the ``s`` flag, such as

    mprof plot -s

.. image:: ./images/trend_slope.png
   :height: 350px

The intended usage of the -s switch is to check the labels' numerical slope over a significant time period for : 

  - ``>0`` it might mean a memory leak.
  - ``~0`` if 0 or near 0, the memory usage may be considered stable.
  - ``<0`` to be interpreted depending on the expected process memory usage patterns, also might mean that the sampling period is too small.

The trend lines are for ilustrative purposes and are plotted as (very) small dashed lines.


Setting debugger breakpoints
=============================
It is possible to set breakpoints depending on the amount of memory used.
That is, you can specify a threshold and as soon as the program uses more
memory than what is specified in the threshold it will stop execution
and run into the pdb debugger. To use it, you will have to decorate
the function as done in the previous section with ``@profile`` and then
run your script with the option ``-m memory_profiler --pdb-mmem=X``,
where X is a number representing the memory threshold in MB. For example::

    $ python -m memory_profiler --pdb-mmem=100 my_script.py

will run ``my_script.py`` and step into the pdb debugger as soon as the code
uses more than 100 MB in the decorated function.

.. TODO: alternatives to decoration (for example when you don't want to modify
    the file where your function lives).

=====
 API
=====
memory_profiler exposes a number of functions to be used in third-party
code.



``memory_usage(proc=-1, interval=.1, timeout=None)`` returns the memory usage
over a time interval. The first argument, ``proc`` represents what
should be monitored.  This can either be the PID of a process (not
necessarily a Python program), a string containing some python code to
be evaluated or a tuple ``(f, args, kw)`` containing a function and its
arguments to be evaluated as ``f(*args, **kw)``. For example,


    >>> from memory_profiler import memory_usage
    >>> mem_usage = memory_usage(-1, interval=.2, timeout=1)
    >>> print(mem_usage)
	[7.296875, 7.296875, 7.296875, 7.296875, 7.296875]


Here I've told memory_profiler to get the memory consumption of the
current process over a period of 1 second with a time interval of 0.2
seconds. As PID I've given it -1, which is a special number (PIDs are
usually positive) that means current process, that is, I'm getting the
memory usage of the current Python interpreter. Thus I'm getting
around 7MB of memory usage from a plain python interpreter. If I try
the same thing on IPython (console) I get 29MB, and if I try the same
thing on the IPython notebook it scales up to 44MB.


If you'd like to get the memory consumption of a Python function, then
you should specify the function and its arguments in the tuple ``(f,
args, kw)``. For example::


    >>> # define a simple function
    >>> def f(a, n=100):
        ...     import time
        ...     time.sleep(2)
        ...     b = [a] * n
        ...     time.sleep(1)
        ...     return b
        ...
    >>> from memory_profiler import memory_usage
    >>> memory_usage((f, (1,), {'n' : int(1e6)}))

This will execute the code `f(1, n=int(1e6))` and return the memory
consumption during this execution.

=========
REPORTING
=========

The output can be redirected to a log file by passing IO stream as
parameter to the decorator like @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

    For details refer: examples/reporting_file.py

``Reporting via logger Module:``

Sometime it would be very convenient to use logger module specially
when we need to use RotatingFileHandler.

The output can be redirected to logger module by simply making use of
LogFile of memory profiler module.

    >>> from memory_profiler import LogFile
    >>> import sys
    >>> sys.stdout = LogFile('memory_profile_log')

``Customized reporting:``

Sending everything to the log file while running the memory_profiler
could be cumbersome and one can choose only entries with increments
by passing True to reportIncrementFlag, where reportIncrementFlag is
a parameter to LogFile class of memory profiler module.

    >>> from memory_profiler import LogFile
    >>> import sys
    >>> sys.stdout = LogFile('memory_profile_log', reportIncrementFlag=False)

    For details refer: examples/reporting_logger.py

=====================
 IPython integration
=====================
After installing the module, if you use IPython, you can use the `%mprun`, `%%mprun`,
`%memit` and `%%memit` magics.

For IPython 0.11+, you can use the module directly as an extension, with
``%load_ext memory_profiler``

To activate it whenever you start IPython, edit the configuration file for your
IPython profile, ~/.ipython/profile_default/ipython_config.py, to register the
extension like this (If you already have other extensions, just add this one to
the list)::

    c.InteractiveShellApp.extensions = [
        'memory_profiler',
    ]

(If the config file doesn't already exist, run ``ipython profile create`` in
a terminal.)

It then can be used directly from IPython to obtain a line-by-line
report using the `%mprun` or `%%mprun` magic command. In this case, you can skip
the `@profile` decorator and instead use the `-f` parameter, like
this. Note however that function my_func must be defined in a file
(cannot have been defined interactively in the Python interpreter)::

    In [1]: from example import my_func, my_func_2

    In [2]: %mprun -f my_func my_func()

or in cell mode::

    In [3]: %%mprun -f my_func -f my_func_2
       ...: my_func()
       ...: my_func_2()

Another useful magic that we define is `%memit`, which is analogous to
`%timeit`. It can be used as follows::

    In [1]: %memit range(10000)
    peak memory: 21.42 MiB, increment: 0.41 MiB

    In [2]: %memit range(1000000)
    peak memory: 52.10 MiB, increment: 31.08 MiB

or in cell mode (with setup code)::

    In [3]: %%memit l=range(1000000)
       ...: len(l)
       ...:
    peak memory: 52.14 MiB, increment: 0.08 MiB

For more details, see the docstrings of the magics.

For IPython 0.10, you can install it by editing the IPython configuration
file ~/.ipython/ipy_user_conf.py to add the following lines::

    # These two lines are standard and probably already there.
    import IPython.ipapi
    ip = IPython.ipapi.get()

    # These two are the important ones.
    import memory_profiler
    memory_profiler.load_ipython_extension(ip)

===============================
Memory tracking backends
===============================
`memory_profiler` supports different memory tracking backends including: 'psutil', 'psutil_pss', 'psutil_uss', 'posix', 'tracemalloc'.
If no specific backend is specified the default is to use "psutil" which measures RSS aka "Resident Set Size". 
In some cases (particularly when tracking child processes) RSS may overestimate memory usage (see `example/example_psutil_memory_full_info.py` for an example).
For more information on "psutil_pss" (measuring PSS) and "psutil_uss" please refer to:
https://psutil.readthedocs.io/en/latest/index.html?highlight=memory_info#psutil.Process.memory_full_info 

Currently, the backend can be set via the CLI

    $ python -m memory_profiler --backend psutil my_script.py

and is exposed by the API

    >>> from memory_profiler import memory_usage
    >>> mem_usage = memory_usage(-1, interval=.2, timeout=1, backend="psutil")

    
============================
 Frequently Asked Questions
============================
    * Q: How accurate are the results ?
    * A: This module gets the memory consumption by querying the
      operating system kernel about the amount of memory the current
      process has allocated, which might be slightly different from
      the amount of memory that is actually used by the Python
      interpreter. Also, because of how the garbage collector works in
      Python the result might be different between platforms and even
      between runs.

    * Q: Does it work under windows ?
    * A: Yes, thanks to the
      `psutil <http://pypi.python.org/pypi/psutil>`_ module.


===========================
 Support, bugs & wish list
===========================
For support, please ask your question on `stack overflow
<http://stackoverflow.com/>`_ and add the `*memory-profiling* tag <http://stackoverflow.com/questions/tagged/memory-profiling>`_.
Send issues, proposals, etc. to `github's issue tracker
<https://github.com/pythonprofilers/memory_profiler/issues>`_ .

If you've got questions regarding development, you can email me
directly at f@bianp.net

.. image:: http://fa.bianp.net/static/tux_memory_small.png


=============
 Development
=============
Latest sources are available from github:

    https://github.com/pythonprofilers/memory_profiler

===============================
Projects using memory_profiler
===============================

`Benchy <https://github.com/python-recsys/benchy>`_

`IPython memory usage <https://github.com/ianozsvald/ipython_memory_usage>`_

`PySpeedIT <https://github.com/peter1000/PySpeedIT>`_ (uses a reduced version of memory_profiler)

`pydio-sync <https://github.com/pydio/pydio-sync>`_ (uses custom wrapper on top of memory_profiler)

=========
 Authors
=========
This module was written by `Fabian Pedregosa <http://fseoane.net>`_
and `Philippe Gervais <https://github.com/pgervais>`_
inspired by Robert Kern's `line profiler
<http://packages.python.org/line_profiler/>`_.

`Tom <http://tomforb.es/>`_ added windows support and speed improvements via the
`psutil <http://pypi.python.org/pypi/psutil>`_ module.

`Victor <https://github.com/octavo>`_ added python3 support, bugfixes and general
cleanup.

`Vlad Niculae <http://vene.ro/>`_ added the `%mprun` and `%memit` IPython magics.

`Thomas Kluyver <https://github.com/takluyver>`_ added the IPython extension.

`Sagar UDAY KUMAR <https://github.com/sagaru>`_ added Report generation feature and examples.

`Dmitriy Novozhilov <https://github.com/demiurg906>`_ and `Sergei Lebedev <https://github.com/superbobry>`_ added support for `tracemalloc <https://docs.python.org/3/library/tracemalloc.html>`_.

`Benjamin Bengfort <https://github.com/bbengfort>`_ added support for tracking the usage of individual child processes and plotting them.

`Muhammad Haseeb Tariq <https://github.com/mhaseebtariq>`_ fixed issue #152, which made the whole interpreter hang on functions that launched an exception.

`Juan Luis Cano <https://github.com/Juanlu001>`_ modernized the infrastructure and helped with various things.

`Martin Becker <https://github.com/mgbckr>`_ added PSS and USS tracking via the psutil backend.

=========
 License
=========
BSD License, see file COPYING for full text.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/pythonprofilers/memory_profiler",
    "name": "memory-profiler",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.5",
    "maintainer_email": "",
    "keywords": "",
    "author": "Fabian Pedregosa",
    "author_email": "f@bianp.net",
    "download_url": "https://files.pythonhosted.org/packages/b2/88/e1907e1ca3488f2d9507ca8b0ae1add7b1cd5d3ca2bc8e5b329382ea2c7b/memory_profiler-0.61.0.tar.gz",
    "platform": null,
    "description": ".. image:: https://travis-ci.org/pythonprofilers/memory_profiler.svg?branch=master\n    :target: https://travis-ci.org/pythonprofilers/memory_profiler\n\n=================\n Memory Profiler\n=================\n\n\n**Note:** This package is no longer actively maintained. I won't be actively responding to issues. If you'd like to volunteer to maintain it, please drop me a line at f@bianp.net\n\nThis is a python module for monitoring memory consumption of a process\nas well as line-by-line analysis of memory consumption for python\nprograms. It is a pure python module which depends on the `psutil\n<http://pypi.python.org/pypi/psutil>`_ module.\n\n\n==============\n Installation\n==============\nInstall via pip::\n\n    $ pip install -U memory_profiler\n\nThe package is also available on `conda-forge\n<https://github.com/conda-forge/memory_profiler-feedstock>`_.\n\nTo install from source, download the package, extract and type::\n\n    $ pip install .\n\n===========\nQuick Start\n===========\n\nUse `mprof` to generate a full memory usage report of your executable and to plot it.\n\n.. code-block:: bash\n\n    mprof run executable\n    mprof plot\n\nThe plot would be something like this:\n\n.. image:: https://i.stack.imgur.com/ixCH4.png\n\n=======\n Usage\n=======\n\n\nline-by-line memory usage\n=========================\n\nThe line-by-line memory usage mode is used much in the same way of the\n`line_profiler <https://pypi.python.org/pypi/line_profiler/>`_: first\ndecorate the function you would like to profile with ``@profile`` and\nthen run the script with a special script (in this case with specific\narguments to the Python interpreter).\n\nIn the following example, we create a simple function ``my_func`` that\nallocates lists ``a``, ``b`` and then deletes ``b``::\n\n\n    @profile\n    def my_func():\n        a = [1] * (10 ** 6)\n        b = [2] * (2 * 10 ** 7)\n        del b\n        return a\n\n    if __name__ == '__main__':\n        my_func()\n\n\nExecute the code passing the option ``-m memory_profiler`` to the\npython interpreter to load the memory_profiler module and print to\nstdout the line-by-line analysis. If the file name was example.py,\nthis would result in::\n\n    $ python -m memory_profiler example.py\n\nOutput will follow::\n\n    Line #    Mem usage    Increment  Occurrences   Line Contents\n    ============================================================\n         3   38.816 MiB   38.816 MiB           1   @profile\n         4                                         def my_func():\n         5   46.492 MiB    7.676 MiB           1       a = [1] * (10 ** 6)\n         6  199.117 MiB  152.625 MiB           1       b = [2] * (2 * 10 ** 7)\n         7   46.629 MiB -152.488 MiB           1       del b\n         8   46.629 MiB    0.000 MiB           1       return a\n\n\nThe first column represents the line number of the code that has been\nprofiled, the second column (*Mem usage*) the memory usage of the\nPython interpreter after that line has been executed. The third column\n(*Increment*) represents the difference in memory of the current line\nwith respect to the last one. The last column (*Line Contents*) prints\nthe code that has been profiled.\n\nDecorator\n=========\nA function decorator is also available.  Use as follows::\n\n    from memory_profiler import profile\n\n    @profile\n    def my_func():\n        a = [1] * (10 ** 6)\n        b = [2] * (2 * 10 ** 7)\n        del b\n        return a\n\nIn this case the script can be run without specifying ``-m\nmemory_profiler`` in the command line.\n\nIn function decorator, you can specify the precision as an argument to the\ndecorator function.  Use as follows::\n\n    from memory_profiler import profile\n\n    @profile(precision=4)\n    def my_func():\n        a = [1] * (10 ** 6)\n        b = [2] * (2 * 10 ** 7)\n        del b\n        return a\n\nIf a python script with decorator ``@profile`` is called using ``-m\nmemory_profiler`` in the command line, the ``precision`` parameter is ignored.\n\nTime-based memory usage\n==========================\nSometimes it is useful to have full memory usage reports as a function of\ntime (not line-by-line) of external processes (be it Python scripts or not).\nIn this case the executable ``mprof`` might be useful. Use it like::\n\n    mprof run <executable>\n    mprof plot\n\nThe first line run the executable and record memory usage along time,\nin a file written in the current directory.\nOnce it's done, a graph plot can be obtained using the second line.\nThe recorded file contains a timestamps, that allows for several\nprofiles to be kept at the same time.\n\nHelp on each `mprof` subcommand can be obtained with the `-h` flag,\ne.g. `mprof run -h`.\n\nIn the case of a Python script, using the previous command does not\ngive you any information on which function is executed at a given\ntime. Depending on the case, it can be difficult to identify the part\nof the code that is causing the highest memory usage.\n\nAdding the `profile` decorator to a function(ensure no \n`from memory_profiler import profile` statement) and running the Python\nscript with\n\n    mprof run --python python <script>\n\nwill record timestamps when entering/leaving the profiled function. Running\n\n    mprof plot\n\nafterward will plot the result, making plots (using matplotlib) similar to these:\n\n.. image:: https://camo.githubusercontent.com/3a584c7cfbae38c9220a755aa21b5ef926c1031d/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313930383631382f3836313332302f63623865376337382d663563632d313165322d386531652d3539373237623636663462322e706e67\n   :target: https://github.com/scikit-learn/scikit-learn/pull/2248\n   :height: 350px\n\nor, with ``mprof plot --flame`` (the function and timestamp names will appear on hover):\n\n.. image:: ./images/flamegraph.png\n   :height: 350px\n\nA discussion of these capabilities can be found `here <http://fa.bianp.net/blog/2014/plot-memory-usage-as-a-function-of-time/>`_.\n\n.. warning:: If your Python file imports the memory profiler `from memory_profiler import profile` these timestamps will not be recorded. Comment out the import, leave your functions decorated, and re-run.\n\nThe available commands for `mprof` are:\n\n  - ``mprof run``: running an executable, recording memory usage\n  - ``mprof plot``: plotting one the recorded memory usage (by default,\n    the last one)\n  - ``mprof list``: listing all recorded memory usage files in a\n    user-friendly way.\n  - ``mprof clean``: removing all recorded memory usage files.\n  - ``mprof rm``: removing specific recorded memory usage files\n\nTracking forked child processes\n===============================\nIn a multiprocessing context the main process will spawn child processes whose\nsystem resources are allocated separately from the parent process. This can\nlead to an inaccurate report of memory usage since by default only the parent\nprocess is being tracked. The ``mprof`` utility provides two mechanisms to\ntrack the usage of child processes: sum the memory of all children to the\nparent's usage and track each child individual.\n\nTo create a report that combines memory usage of all the children and the\nparent, use the ``include-children`` flag in either the ``profile`` decorator or\nas a command line argument to ``mprof``::\n\n    mprof run --include-children <script>\n\nThe second method tracks each child independently of the main process,\nserializing child rows by index to the output stream. Use the ``multiprocess``\nflag and plot as follows::\n\n    mprof run --multiprocess <script>\n    mprof plot\n\nThis will create a plot using matplotlib similar to this:\n\n.. image:: https://cloud.githubusercontent.com/assets/745966/24075879/2e85b43a-0bfa-11e7-8dfe-654320dbd2ce.png\n    :target: https://github.com/pythonprofilers/memory_profiler/pull/134\n    :height: 350px\n\nYou can combine both the ``include-children`` and ``multiprocess`` flags to show\nthe total memory of the program as well as each child individually. If using\nthe API directly, note that the return from ``memory_usage`` will include the\nchild memory in a nested list along with the main process memory.\n\nPlot settings\n===============================\n\nBy default, the command line call is set as the graph title. If you wish to customize it, you can use the ``-t`` option to manually set the figure title.\n\n\n    mprof plot -t 'Recorded memory usage'\n\nYou can also hide the function timestamps using the ``n`` flag, such as\n\n    mprof plot -n\n\nTrend lines and its numeric slope can be plotted using the ``s`` flag, such as\n\n    mprof plot -s\n\n.. image:: ./images/trend_slope.png\n   :height: 350px\n\nThe intended usage of the -s switch is to check the labels' numerical slope over a significant time period for : \n\n  - ``>0`` it might mean a memory leak.\n  - ``~0`` if 0 or near 0, the memory usage may be considered stable.\n  - ``<0`` to be interpreted depending on the expected process memory usage patterns, also might mean that the sampling period is too small.\n\nThe trend lines are for ilustrative purposes and are plotted as (very) small dashed lines.\n\n\nSetting debugger breakpoints\n=============================\nIt is possible to set breakpoints depending on the amount of memory used.\nThat is, you can specify a threshold and as soon as the program uses more\nmemory than what is specified in the threshold it will stop execution\nand run into the pdb debugger. To use it, you will have to decorate\nthe function as done in the previous section with ``@profile`` and then\nrun your script with the option ``-m memory_profiler --pdb-mmem=X``,\nwhere X is a number representing the memory threshold in MB. For example::\n\n    $ python -m memory_profiler --pdb-mmem=100 my_script.py\n\nwill run ``my_script.py`` and step into the pdb debugger as soon as the code\nuses more than 100 MB in the decorated function.\n\n.. TODO: alternatives to decoration (for example when you don't want to modify\n    the file where your function lives).\n\n=====\n API\n=====\nmemory_profiler exposes a number of functions to be used in third-party\ncode.\n\n\n\n``memory_usage(proc=-1, interval=.1, timeout=None)`` returns the memory usage\nover a time interval. The first argument, ``proc`` represents what\nshould be monitored.  This can either be the PID of a process (not\nnecessarily a Python program), a string containing some python code to\nbe evaluated or a tuple ``(f, args, kw)`` containing a function and its\narguments to be evaluated as ``f(*args, **kw)``. For example,\n\n\n    >>> from memory_profiler import memory_usage\n    >>> mem_usage = memory_usage(-1, interval=.2, timeout=1)\n    >>> print(mem_usage)\n\t[7.296875, 7.296875, 7.296875, 7.296875, 7.296875]\n\n\nHere I've told memory_profiler to get the memory consumption of the\ncurrent process over a period of 1 second with a time interval of 0.2\nseconds. As PID I've given it -1, which is a special number (PIDs are\nusually positive) that means current process, that is, I'm getting the\nmemory usage of the current Python interpreter. Thus I'm getting\naround 7MB of memory usage from a plain python interpreter. If I try\nthe same thing on IPython (console) I get 29MB, and if I try the same\nthing on the IPython notebook it scales up to 44MB.\n\n\nIf you'd like to get the memory consumption of a Python function, then\nyou should specify the function and its arguments in the tuple ``(f,\nargs, kw)``. For example::\n\n\n    >>> # define a simple function\n    >>> def f(a, n=100):\n        ...     import time\n        ...     time.sleep(2)\n        ...     b = [a] * n\n        ...     time.sleep(1)\n        ...     return b\n        ...\n    >>> from memory_profiler import memory_usage\n    >>> memory_usage((f, (1,), {'n' : int(1e6)}))\n\nThis will execute the code `f(1, n=int(1e6))` and return the memory\nconsumption during this execution.\n\n=========\nREPORTING\n=========\n\nThe output can be redirected to a log file by passing IO stream as\nparameter to the decorator like @profile(stream=fp)\n\n    >>> fp=open('memory_profiler.log','w+')\n    >>> @profile(stream=fp)\n    >>> def my_func():\n        ...     a = [1] * (10 ** 6)\n        ...     b = [2] * (2 * 10 ** 7)\n        ...     del b\n        ...     return a\n\n    For details refer: examples/reporting_file.py\n\n``Reporting via logger Module:``\n\nSometime it would be very convenient to use logger module specially\nwhen we need to use RotatingFileHandler.\n\nThe output can be redirected to logger module by simply making use of\nLogFile of memory profiler module.\n\n    >>> from memory_profiler import LogFile\n    >>> import sys\n    >>> sys.stdout = LogFile('memory_profile_log')\n\n``Customized reporting:``\n\nSending everything to the log file while running the memory_profiler\ncould be cumbersome and one can choose only entries with increments\nby passing True to reportIncrementFlag, where reportIncrementFlag is\na parameter to LogFile class of memory profiler module.\n\n    >>> from memory_profiler import LogFile\n    >>> import sys\n    >>> sys.stdout = LogFile('memory_profile_log', reportIncrementFlag=False)\n\n    For details refer: examples/reporting_logger.py\n\n=====================\n IPython integration\n=====================\nAfter installing the module, if you use IPython, you can use the `%mprun`, `%%mprun`,\n`%memit` and `%%memit` magics.\n\nFor IPython 0.11+, you can use the module directly as an extension, with\n``%load_ext memory_profiler``\n\nTo activate it whenever you start IPython, edit the configuration file for your\nIPython profile, ~/.ipython/profile_default/ipython_config.py, to register the\nextension like this (If you already have other extensions, just add this one to\nthe list)::\n\n    c.InteractiveShellApp.extensions = [\n        'memory_profiler',\n    ]\n\n(If the config file doesn't already exist, run ``ipython profile create`` in\na terminal.)\n\nIt then can be used directly from IPython to obtain a line-by-line\nreport using the `%mprun` or `%%mprun` magic command. In this case, you can skip\nthe `@profile` decorator and instead use the `-f` parameter, like\nthis. Note however that function my_func must be defined in a file\n(cannot have been defined interactively in the Python interpreter)::\n\n    In [1]: from example import my_func, my_func_2\n\n    In [2]: %mprun -f my_func my_func()\n\nor in cell mode::\n\n    In [3]: %%mprun -f my_func -f my_func_2\n       ...: my_func()\n       ...: my_func_2()\n\nAnother useful magic that we define is `%memit`, which is analogous to\n`%timeit`. It can be used as follows::\n\n    In [1]: %memit range(10000)\n    peak memory: 21.42 MiB, increment: 0.41 MiB\n\n    In [2]: %memit range(1000000)\n    peak memory: 52.10 MiB, increment: 31.08 MiB\n\nor in cell mode (with setup code)::\n\n    In [3]: %%memit l=range(1000000)\n       ...: len(l)\n       ...:\n    peak memory: 52.14 MiB, increment: 0.08 MiB\n\nFor more details, see the docstrings of the magics.\n\nFor IPython 0.10, you can install it by editing the IPython configuration\nfile ~/.ipython/ipy_user_conf.py to add the following lines::\n\n    # These two lines are standard and probably already there.\n    import IPython.ipapi\n    ip = IPython.ipapi.get()\n\n    # These two are the important ones.\n    import memory_profiler\n    memory_profiler.load_ipython_extension(ip)\n\n===============================\nMemory tracking backends\n===============================\n`memory_profiler` supports different memory tracking backends including: 'psutil', 'psutil_pss', 'psutil_uss', 'posix', 'tracemalloc'.\nIf no specific backend is specified the default is to use \"psutil\" which measures RSS aka \"Resident Set Size\". \nIn some cases (particularly when tracking child processes) RSS may overestimate memory usage (see `example/example_psutil_memory_full_info.py` for an example).\nFor more information on \"psutil_pss\" (measuring PSS) and \"psutil_uss\" please refer to:\nhttps://psutil.readthedocs.io/en/latest/index.html?highlight=memory_info#psutil.Process.memory_full_info \n\nCurrently, the backend can be set via the CLI\n\n    $ python -m memory_profiler --backend psutil my_script.py\n\nand is exposed by the API\n\n    >>> from memory_profiler import memory_usage\n    >>> mem_usage = memory_usage(-1, interval=.2, timeout=1, backend=\"psutil\")\n\n    \n============================\n Frequently Asked Questions\n============================\n    * Q: How accurate are the results ?\n    * A: This module gets the memory consumption by querying the\n      operating system kernel about the amount of memory the current\n      process has allocated, which might be slightly different from\n      the amount of memory that is actually used by the Python\n      interpreter. Also, because of how the garbage collector works in\n      Python the result might be different between platforms and even\n      between runs.\n\n    * Q: Does it work under windows ?\n    * A: Yes, thanks to the\n      `psutil <http://pypi.python.org/pypi/psutil>`_ module.\n\n\n===========================\n Support, bugs & wish list\n===========================\nFor support, please ask your question on `stack overflow\n<http://stackoverflow.com/>`_ and add the `*memory-profiling* tag <http://stackoverflow.com/questions/tagged/memory-profiling>`_.\nSend issues, proposals, etc. to `github's issue tracker\n<https://github.com/pythonprofilers/memory_profiler/issues>`_ .\n\nIf you've got questions regarding development, you can email me\ndirectly at f@bianp.net\n\n.. image:: http://fa.bianp.net/static/tux_memory_small.png\n\n\n=============\n Development\n=============\nLatest sources are available from github:\n\n    https://github.com/pythonprofilers/memory_profiler\n\n===============================\nProjects using memory_profiler\n===============================\n\n`Benchy <https://github.com/python-recsys/benchy>`_\n\n`IPython memory usage <https://github.com/ianozsvald/ipython_memory_usage>`_\n\n`PySpeedIT <https://github.com/peter1000/PySpeedIT>`_ (uses a reduced version of memory_profiler)\n\n`pydio-sync <https://github.com/pydio/pydio-sync>`_ (uses custom wrapper on top of memory_profiler)\n\n=========\n Authors\n=========\nThis module was written by `Fabian Pedregosa <http://fseoane.net>`_\nand `Philippe Gervais <https://github.com/pgervais>`_\ninspired by Robert Kern's `line profiler\n<http://packages.python.org/line_profiler/>`_.\n\n`Tom <http://tomforb.es/>`_ added windows support and speed improvements via the\n`psutil <http://pypi.python.org/pypi/psutil>`_ module.\n\n`Victor <https://github.com/octavo>`_ added python3 support, bugfixes and general\ncleanup.\n\n`Vlad Niculae <http://vene.ro/>`_ added the `%mprun` and `%memit` IPython magics.\n\n`Thomas Kluyver <https://github.com/takluyver>`_ added the IPython extension.\n\n`Sagar UDAY KUMAR <https://github.com/sagaru>`_ added Report generation feature and examples.\n\n`Dmitriy Novozhilov <https://github.com/demiurg906>`_ and `Sergei Lebedev <https://github.com/superbobry>`_ added support for `tracemalloc <https://docs.python.org/3/library/tracemalloc.html>`_.\n\n`Benjamin Bengfort <https://github.com/bbengfort>`_ added support for tracking the usage of individual child processes and plotting them.\n\n`Muhammad Haseeb Tariq <https://github.com/mhaseebtariq>`_ fixed issue #152, which made the whole interpreter hang on functions that launched an exception.\n\n`Juan Luis Cano <https://github.com/Juanlu001>`_ modernized the infrastructure and helped with various things.\n\n`Martin Becker <https://github.com/mgbckr>`_ added PSS and USS tracking via the psutil backend.\n\n=========\n License\n=========\nBSD License, see file COPYING for full text.\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "A module for monitoring memory usage of a python program",
    "version": "0.61.0",
    "project_urls": {
        "Homepage": "https://github.com/pythonprofilers/memory_profiler"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4926aaca612a0634ceede20682e692a6c55e35a94c21ba36b807cc40fe910ae1",
                "md5": "fad3e16d09ae00191548c86471cb204c",
                "sha256": "400348e61031e3942ad4d4109d18753b2fb08c2f6fb8290671c5513a34182d84"
            },
            "downloads": -1,
            "filename": "memory_profiler-0.61.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "fad3e16d09ae00191548c86471cb204c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.5",
            "size": 31803,
            "upload_time": "2022-11-15T17:57:27",
            "upload_time_iso_8601": "2022-11-15T17:57:27.031808Z",
            "url": "https://files.pythonhosted.org/packages/49/26/aaca612a0634ceede20682e692a6c55e35a94c21ba36b807cc40fe910ae1/memory_profiler-0.61.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b288e1907e1ca3488f2d9507ca8b0ae1add7b1cd5d3ca2bc8e5b329382ea2c7b",
                "md5": "5fe93d5035288095c4f86ef69ee19f37",
                "sha256": "4e5b73d7864a1d1292fb76a03e82a3e78ef934d06828a698d9dada76da2067b0"
            },
            "downloads": -1,
            "filename": "memory_profiler-0.61.0.tar.gz",
            "has_sig": false,
            "md5_digest": "5fe93d5035288095c4f86ef69ee19f37",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.5",
            "size": 35935,
            "upload_time": "2022-11-15T17:57:28",
            "upload_time_iso_8601": "2022-11-15T17:57:28.994274Z",
            "url": "https://files.pythonhosted.org/packages/b2/88/e1907e1ca3488f2d9507ca8b0ae1add7b1cd5d3ca2bc8e5b329382ea2c7b/memory_profiler-0.61.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-11-15 17:57:28",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "pythonprofilers",
    "github_project": "memory_profiler",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "memory-profiler"
}
        
Elapsed time: 1.25614s