timerit


Nametimerit JSON
Version 1.1.0 PyPI version JSON
download
home_pagehttps://github.com/Erotemic/timerit
SummaryA powerful multiline alternative to timeit
upload_time2023-08-13 22:58:32
maintainer
docs_urlNone
authorJon Crall
requires_python>=3.6
licenseApache 2
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            
|GithubActions| |Appveyor| |Codecov| |Pypi| |Downloads| |ReadTheDocs|


Timerit
=======

A powerful multiline alternative to Python's builtin ``timeit`` module.

Docs are published at https://timerit.readthedocs.io/en/latest/ but this README
and code comments contain a walkthrough.

+---------------+--------------------------------------------+
| Github        | https://github.com/Erotemic/timerit        |
+---------------+--------------------------------------------+
| Pypi          | https://pypi.org/project/timerit           |
+---------------+--------------------------------------------+
| ReadTheDocs   | https://timerit.readthedocs.io/en/latest/  |
+---------------+--------------------------------------------+

Description
-----------

Easily do robust timings on existing blocks of code by simply indenting
them. There is no need to refactor into a string representation or
convert to a single line.

Installation
------------

.. code:: bash

    pip install timerit


Interactive Use
---------------

The ``timerit`` library provides a succinct API for interactive use:

.. code:: python

    >>> import timerit
    >>> for _ in timerit:
    ...     sum(range(100000))
    Timed for: 288 loops, best of 5
        time per loop: best=616.740 µs, mean=668.933 ± 124.2 µs

Compare to ``timeit``:

.. code:: bash

    $ python -m timeit 'sum(range(100000))'
    500 loops, best of 5: 721 usec per loop

By default, any code within the loop will be repeatedly executed until at least
200 ms have elapsed.  The timing results are then printed out.

Here's what each of the numbers means:

- "288 loops": The code in the loop was run 288 times before the time limit was
  reached.

- "best of 5": Consider only the fastest of every 5 measured times, when
  calculating the mean and standard deviation.  The reason for doing this is
  that you can get slow times if the something in the background is consuming
  resources, so you're generally only interested in the fastest times.  This
  idea is also described in the
  `timeit <https://docs.python.org/3/library/timeit.html#timeit.Timer.repeat>`_ docs.

- "best=616.740 µs": How long the fastest iteration took to run.  For the reasons
  described above, this is usually the most consistent number, and the primary
  number you should focus on.

- "mean=668.933 ± 124.2 µs": The mean and the standard deviation of the "best of 5"
  iterations.  This statistic is usually not as robust or useful as the fastest
  time, but sometimes its helpful to know if there's high variance.

The loop variable can be used as a context manager to only time a part of each
loop (e.g. to make the timings more accurate, or to incorporate a setup phase
that is not timed):

.. code:: python

    >>> for timer in timerit:
    ...     n = 100 * 1000
    ...     with timer:
    ...         sum(range(n))
    Timed for: 318 loops, best of 5
        time per loop: best=616.673 µs, mean=617.545 ± 0.9 µs

It is also possible to provide arguments controlling how the timing
measurements are made.  See the online documentation for more information on
these arguments, but the snippet below runs for exactly 100 iterations, instead
of however many fit in 200 ms.

.. code:: python

    >>> for _ in timerit(num=100):
    ...     sum(range(100000))
    Timed for: 100 loops, best of 5
        time per loop: best=616.866 µs, mean=619.120 ± 5.3 µs


Automatic Import
~~~~~~~~~~~~~~~~
If you want to make ``timerit`` even easier to use interactively, you can move
the import to the PYTHONSTARTUP_ file.  If defined, this environment variable
gives the path to a python script that will be executed just before every
interactive session.  For example:

.. code:: bash

    $ export PYTHONSTARTUP=~/.pythonrc
    $ cat $PYTHONSTARTUP
    import timerit
    $ python
    >>> for _ in timerit:
    ...     sum(range(100000))
    ...
    Timed for: 59 loops, best of 3
        time per loop: best=2.532 ms, mean=3.309 ± 1.0 ms


Programmatic Use
----------------

The timerit library also provides a ``Timerit`` class that can be used
programmatically.

.. code:: python

    >>> import math, timerit
    >>> for timer in timerit:
    >>>     setup_vars = 10000
    >>>     with timer:
    >>>         math.factorial(setup_vars)
    >>> print('t1.total_time = %r' % (t1.total_time,))
    Timing for 200 loops
    Timed for: 200 loops, best of 3
        time per loop: best=2.064 ms, mean=2.115 ± 0.05 ms
    t1.total_time = 0.4427177629695507

A common pattern is to create a single ``Timerit`` instance, then to repeatedly
"reset" it with different labels to test a number of different algorithms.  The
labels assigned in this way will be incorporated into the report strings that
the ``Timerit`` instance produces.  The "Benchmark Recipe" below shows an example
of this pattern.  So do all of the scripts in the ``examples/`` directory.

There is also a simple one-liner that is comparable to ``timeit``'s IPython magic:

Compare the timeit version:

.. code:: python

    >>> %timeit math.factorial(100)
    564 ns ± 5.46 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

With the Timerit version:

.. code:: python

    >>> Timerit(100000).call(math.factorial, 100).print()
    Timed for: 1 loops, best of 1
        time per loop: best=4.828 µs, mean=4.828 ± 0.0 µs


How it works
------------

The timerit module defines ``timerit.Timerit``, which is an iterable object
that yields ``timerit.Timer`` context managers.

.. code:: python

    >>> import math
    >>> from timerit import Timerit
    >>> for timer in Timerit(num=200, verbose=2):
    >>>     with timer:
    >>>         math.factorial(10000)

The timer context manager measures how much time the body of it takes by
"tic"-ing on ``__enter__`` and "toc"-ing on ``__exit__``. The parent
``Timerit`` object has access to the context manager, so it is able to read its
measurement. These measurements are stored and then we compute some statistics
on them. Notably the minimum, mean, and standard-deviation of grouped (batched)
running times.

Using the with statement inside the loop is nice because you can run untimed
setup code before you enter the context manager.

In the case where no setup code is required, a more concise version of the
syntax is available.

.. code:: python

    >>> import math
    >>> from timerit import Timerit
    >>> for _ in Timerit(num=200, verbose=2):
    >>>     math.factorial(10000)

If the context manager is never called, the ``Timerit`` object detects this and
the measurement is made in the ``__iter__`` method in the ``Timerit`` object
itself. I believe that this concise method contains slightly more overhead than
the with-statement version. (I have seen evidence that this might actually be
more accurate, but it needs further testing).

Benchmark Recipe
----------------

.. code:: python

    import ubelt as ub
    import pandas as pd
    import timerit

    def method1(x):
        ret = []
        for i in range(x):
            ret.append(i)
        return ret

    def method2(x):
        ret = [i for i in range(x)]
        return ret

    method_lut = locals()  # can populate this some other way

    ti = timerit.Timerit(100, bestof=10, verbose=2)

    basis = {
        'method': ['method1', 'method2'],
        'x': list(range(7)),
        # 'param_name': [param values],
    }
    grid_iter = ub.named_product(basis)

    # For each variation of your experiment, create a row.
    rows = []
    for params in grid_iter:
        key = ub.repr2(params, compact=1, si=1)
        kwargs = params.copy()
        method_key = kwargs.pop('method')
        method = method_lut[method_key]
        # Timerit will run some user-specified number of loops.
        # and compute time stats with similar methodology to timeit
        for timer in ti.reset(key):
            # Put any setup logic you dont want to time here.
            # ...
            with timer:
                # Put the logic you want to time here
                method(**kwargs)
        row = {
            'mean': ti.mean(),
            'min': ti.min(),
            'key': key,
            **params,
        }
        rows.append(row)

    # The rows define a long-form pandas data array.
    # Data in long-form makes it very easy to use seaborn.
    data = pd.DataFrame(rows)
    print(data)

    plot = True
    if plot:
        # import seaborn as sns
        # kwplot autosns works well for IPython and script execution.
        # not sure about notebooks.
        import kwplot
        sns = kwplot.autosns()

        # Your variables may change
        ax = kwplot.figure(fnum=1, doclf=True).gca()
        sns.lineplot(data=data, x='x', y='min', hue='method', marker='o', ax=ax)
        ax.set_title('Benchmark Name')
        ax.set_xlabel('x-variable description')
        ax.set_ylabel('y-variable description')


.. |Travis| image:: https://img.shields.io/travis/Erotemic/timerit/master.svg?label=Travis%20CI
   :target: https://travis-ci.org/Erotemic/timerit?branch=master
.. |Codecov| image:: https://codecov.io/github/Erotemic/timerit/badge.svg?branch=master&service=github
   :target: https://codecov.io/github/Erotemic/timerit?branch=master
.. |Appveyor| image:: https://ci.appveyor.com/api/projects/status/github/Erotemic/timerit?branch=master&svg=True
   :target: https://ci.appveyor.com/project/Erotemic/timerit/branch/master
.. |Pypi| image:: https://img.shields.io/pypi/v/timerit.svg
   :target: https://pypi.python.org/pypi/timerit
.. |Downloads| image:: https://img.shields.io/pypi/dm/timerit.svg
   :target: https://pypistats.org/packages/timerit
.. |CircleCI| image:: https://circleci.com/gh/Erotemic/timerit.svg?style=svg
    :target: https://circleci.com/gh/Erotemic/timerit
.. |ReadTheDocs| image:: https://readthedocs.org/projects/timerit/badge/?version=latest
    :target: http://timerit.readthedocs.io/en/latest/
.. |CodeQuality| image:: https://api.codacy.com/project/badge/Grade/fdcedca723f24ec4be9c7067d91cb43b
    :target: https://www.codacy.com/manual/Erotemic/timerit?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=Erotemic/timerit&amp;utm_campaign=Badge_Grade
.. |GithubActions| image:: https://github.com/Erotemic/timerit/actions/workflows/tests.yml/badge.svg?branch=main
    :target: https://github.com/Erotemic/timerit/actions?query=branch%3Amain

.. _PYTHONSTARTUP: https://docs.python.org/3/using/cmdline.html?highlight=pythonstartup#envvar-PYTHONSTARTUP




            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Erotemic/timerit",
    "name": "timerit",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "",
    "author": "Jon Crall",
    "author_email": "erotemic@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/63/d6/36252ff3d6a0bfaa3fa54e025d671df949b265b426429e7e8ab0149e65c2/timerit-1.1.0.tar.gz",
    "platform": null,
    "description": "\n|GithubActions| |Appveyor| |Codecov| |Pypi| |Downloads| |ReadTheDocs|\n\n\nTimerit\n=======\n\nA powerful multiline alternative to Python's builtin ``timeit`` module.\n\nDocs are published at https://timerit.readthedocs.io/en/latest/ but this README\nand code comments contain a walkthrough.\n\n+---------------+--------------------------------------------+\n| Github        | https://github.com/Erotemic/timerit        |\n+---------------+--------------------------------------------+\n| Pypi          | https://pypi.org/project/timerit           |\n+---------------+--------------------------------------------+\n| ReadTheDocs   | https://timerit.readthedocs.io/en/latest/  |\n+---------------+--------------------------------------------+\n\nDescription\n-----------\n\nEasily do robust timings on existing blocks of code by simply indenting\nthem. There is no need to refactor into a string representation or\nconvert to a single line.\n\nInstallation\n------------\n\n.. code:: bash\n\n    pip install timerit\n\n\nInteractive Use\n---------------\n\nThe ``timerit`` library provides a succinct API for interactive use:\n\n.. code:: python\n\n    >>> import timerit\n    >>> for _ in timerit:\n    ...     sum(range(100000))\n    Timed for: 288 loops, best of 5\n        time per loop: best=616.740 \u00b5s, mean=668.933 \u00b1 124.2 \u00b5s\n\nCompare to ``timeit``:\n\n.. code:: bash\n\n    $ python -m timeit 'sum(range(100000))'\n    500 loops, best of 5: 721 usec per loop\n\nBy default, any code within the loop will be repeatedly executed until at least\n200 ms have elapsed.  The timing results are then printed out.\n\nHere's what each of the numbers means:\n\n- \"288 loops\": The code in the loop was run 288 times before the time limit was\n  reached.\n\n- \"best of 5\": Consider only the fastest of every 5 measured times, when\n  calculating the mean and standard deviation.  The reason for doing this is\n  that you can get slow times if the something in the background is consuming\n  resources, so you're generally only interested in the fastest times.  This\n  idea is also described in the\n  `timeit <https://docs.python.org/3/library/timeit.html#timeit.Timer.repeat>`_ docs.\n\n- \"best=616.740 \u00b5s\": How long the fastest iteration took to run.  For the reasons\n  described above, this is usually the most consistent number, and the primary\n  number you should focus on.\n\n- \"mean=668.933 \u00b1 124.2 \u00b5s\": The mean and the standard deviation of the \"best of 5\"\n  iterations.  This statistic is usually not as robust or useful as the fastest\n  time, but sometimes its helpful to know if there's high variance.\n\nThe loop variable can be used as a context manager to only time a part of each\nloop (e.g. to make the timings more accurate, or to incorporate a setup phase\nthat is not timed):\n\n.. code:: python\n\n    >>> for timer in timerit:\n    ...     n = 100 * 1000\n    ...     with timer:\n    ...         sum(range(n))\n    Timed for: 318 loops, best of 5\n        time per loop: best=616.673 \u00b5s, mean=617.545 \u00b1 0.9 \u00b5s\n\nIt is also possible to provide arguments controlling how the timing\nmeasurements are made.  See the online documentation for more information on\nthese arguments, but the snippet below runs for exactly 100 iterations, instead\nof however many fit in 200 ms.\n\n.. code:: python\n\n    >>> for _ in timerit(num=100):\n    ...     sum(range(100000))\n    Timed for: 100 loops, best of 5\n        time per loop: best=616.866 \u00b5s, mean=619.120 \u00b1 5.3 \u00b5s\n\n\nAutomatic Import\n~~~~~~~~~~~~~~~~\nIf you want to make ``timerit`` even easier to use interactively, you can move\nthe import to the PYTHONSTARTUP_ file.  If defined, this environment variable\ngives the path to a python script that will be executed just before every\ninteractive session.  For example:\n\n.. code:: bash\n\n    $ export PYTHONSTARTUP=~/.pythonrc\n    $ cat $PYTHONSTARTUP\n    import timerit\n    $ python\n    >>> for _ in timerit:\n    ...     sum(range(100000))\n    ...\n    Timed for: 59 loops, best of 3\n        time per loop: best=2.532 ms, mean=3.309 \u00b1 1.0 ms\n\n\nProgrammatic Use\n----------------\n\nThe timerit library also provides a ``Timerit`` class that can be used\nprogrammatically.\n\n.. code:: python\n\n    >>> import math, timerit\n    >>> for timer in timerit:\n    >>>     setup_vars = 10000\n    >>>     with timer:\n    >>>         math.factorial(setup_vars)\n    >>> print('t1.total_time = %r' % (t1.total_time,))\n    Timing for 200 loops\n    Timed for: 200 loops, best of 3\n        time per loop: best=2.064 ms, mean=2.115 \u00b1 0.05 ms\n    t1.total_time = 0.4427177629695507\n\nA common pattern is to create a single ``Timerit`` instance, then to repeatedly\n\"reset\" it with different labels to test a number of different algorithms.  The\nlabels assigned in this way will be incorporated into the report strings that\nthe ``Timerit`` instance produces.  The \"Benchmark Recipe\" below shows an example\nof this pattern.  So do all of the scripts in the ``examples/`` directory.\n\nThere is also a simple one-liner that is comparable to ``timeit``'s IPython magic:\n\nCompare the timeit version:\n\n.. code:: python\n\n    >>> %timeit math.factorial(100)\n    564 ns \u00b1 5.46 ns per loop (mean \u00b1 std. dev. of 7 runs, 1000000 loops each)\n\nWith the Timerit version:\n\n.. code:: python\n\n    >>> Timerit(100000).call(math.factorial, 100).print()\n    Timed for: 1 loops, best of 1\n        time per loop: best=4.828 \u00b5s, mean=4.828 \u00b1 0.0 \u00b5s\n\n\nHow it works\n------------\n\nThe timerit module defines ``timerit.Timerit``, which is an iterable object\nthat yields ``timerit.Timer`` context managers.\n\n.. code:: python\n\n    >>> import math\n    >>> from timerit import Timerit\n    >>> for timer in Timerit(num=200, verbose=2):\n    >>>     with timer:\n    >>>         math.factorial(10000)\n\nThe timer context manager measures how much time the body of it takes by\n\"tic\"-ing on ``__enter__`` and \"toc\"-ing on ``__exit__``. The parent\n``Timerit`` object has access to the context manager, so it is able to read its\nmeasurement. These measurements are stored and then we compute some statistics\non them. Notably the minimum, mean, and standard-deviation of grouped (batched)\nrunning times.\n\nUsing the with statement inside the loop is nice because you can run untimed\nsetup code before you enter the context manager.\n\nIn the case where no setup code is required, a more concise version of the\nsyntax is available.\n\n.. code:: python\n\n    >>> import math\n    >>> from timerit import Timerit\n    >>> for _ in Timerit(num=200, verbose=2):\n    >>>     math.factorial(10000)\n\nIf the context manager is never called, the ``Timerit`` object detects this and\nthe measurement is made in the ``__iter__`` method in the ``Timerit`` object\nitself. I believe that this concise method contains slightly more overhead than\nthe with-statement version. (I have seen evidence that this might actually be\nmore accurate, but it needs further testing).\n\nBenchmark Recipe\n----------------\n\n.. code:: python\n\n    import ubelt as ub\n    import pandas as pd\n    import timerit\n\n    def method1(x):\n        ret = []\n        for i in range(x):\n            ret.append(i)\n        return ret\n\n    def method2(x):\n        ret = [i for i in range(x)]\n        return ret\n\n    method_lut = locals()  # can populate this some other way\n\n    ti = timerit.Timerit(100, bestof=10, verbose=2)\n\n    basis = {\n        'method': ['method1', 'method2'],\n        'x': list(range(7)),\n        # 'param_name': [param values],\n    }\n    grid_iter = ub.named_product(basis)\n\n    # For each variation of your experiment, create a row.\n    rows = []\n    for params in grid_iter:\n        key = ub.repr2(params, compact=1, si=1)\n        kwargs = params.copy()\n        method_key = kwargs.pop('method')\n        method = method_lut[method_key]\n        # Timerit will run some user-specified number of loops.\n        # and compute time stats with similar methodology to timeit\n        for timer in ti.reset(key):\n            # Put any setup logic you dont want to time here.\n            # ...\n            with timer:\n                # Put the logic you want to time here\n                method(**kwargs)\n        row = {\n            'mean': ti.mean(),\n            'min': ti.min(),\n            'key': key,\n            **params,\n        }\n        rows.append(row)\n\n    # The rows define a long-form pandas data array.\n    # Data in long-form makes it very easy to use seaborn.\n    data = pd.DataFrame(rows)\n    print(data)\n\n    plot = True\n    if plot:\n        # import seaborn as sns\n        # kwplot autosns works well for IPython and script execution.\n        # not sure about notebooks.\n        import kwplot\n        sns = kwplot.autosns()\n\n        # Your variables may change\n        ax = kwplot.figure(fnum=1, doclf=True).gca()\n        sns.lineplot(data=data, x='x', y='min', hue='method', marker='o', ax=ax)\n        ax.set_title('Benchmark Name')\n        ax.set_xlabel('x-variable description')\n        ax.set_ylabel('y-variable description')\n\n\n.. |Travis| image:: https://img.shields.io/travis/Erotemic/timerit/master.svg?label=Travis%20CI\n   :target: https://travis-ci.org/Erotemic/timerit?branch=master\n.. |Codecov| image:: https://codecov.io/github/Erotemic/timerit/badge.svg?branch=master&service=github\n   :target: https://codecov.io/github/Erotemic/timerit?branch=master\n.. |Appveyor| image:: https://ci.appveyor.com/api/projects/status/github/Erotemic/timerit?branch=master&svg=True\n   :target: https://ci.appveyor.com/project/Erotemic/timerit/branch/master\n.. |Pypi| image:: https://img.shields.io/pypi/v/timerit.svg\n   :target: https://pypi.python.org/pypi/timerit\n.. |Downloads| image:: https://img.shields.io/pypi/dm/timerit.svg\n   :target: https://pypistats.org/packages/timerit\n.. |CircleCI| image:: https://circleci.com/gh/Erotemic/timerit.svg?style=svg\n    :target: https://circleci.com/gh/Erotemic/timerit\n.. |ReadTheDocs| image:: https://readthedocs.org/projects/timerit/badge/?version=latest\n    :target: http://timerit.readthedocs.io/en/latest/\n.. |CodeQuality| image:: https://api.codacy.com/project/badge/Grade/fdcedca723f24ec4be9c7067d91cb43b\n    :target: https://www.codacy.com/manual/Erotemic/timerit?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=Erotemic/timerit&amp;utm_campaign=Badge_Grade\n.. |GithubActions| image:: https://github.com/Erotemic/timerit/actions/workflows/tests.yml/badge.svg?branch=main\n    :target: https://github.com/Erotemic/timerit/actions?query=branch%3Amain\n\n.. _PYTHONSTARTUP: https://docs.python.org/3/using/cmdline.html?highlight=pythonstartup#envvar-PYTHONSTARTUP\n\n\n\n",
    "bugtrack_url": null,
    "license": "Apache 2",
    "summary": "A powerful multiline alternative to timeit",
    "version": "1.1.0",
    "project_urls": {
        "Homepage": "https://github.com/Erotemic/timerit"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c35e707d015e882426ac8b5e703a242032eafa9df21ce4851d75b867791e1246",
                "md5": "2580e25ef80be4b61ad98d30c79dc73e",
                "sha256": "20e330a6da00295e1a1f88b2c89e18f6f55e785486da817de5762c3c06a0c2e2"
            },
            "downloads": -1,
            "filename": "timerit-1.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2580e25ef80be4b61ad98d30c79dc73e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 22187,
            "upload_time": "2023-08-13T22:58:30",
            "upload_time_iso_8601": "2023-08-13T22:58:30.408261Z",
            "url": "https://files.pythonhosted.org/packages/c3/5e/707d015e882426ac8b5e703a242032eafa9df21ce4851d75b867791e1246/timerit-1.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "63d636252ff3d6a0bfaa3fa54e025d671df949b265b426429e7e8ab0149e65c2",
                "md5": "27efd603358cefd2f21a0bab303ba9d6",
                "sha256": "a12a7db82d8cc6a0e1bc3258e6eead7a21c617da5605083118d5c3e99927fb69"
            },
            "downloads": -1,
            "filename": "timerit-1.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "27efd603358cefd2f21a0bab303ba9d6",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 27142,
            "upload_time": "2023-08-13T22:58:32",
            "upload_time_iso_8601": "2023-08-13T22:58:32.633462Z",
            "url": "https://files.pythonhosted.org/packages/63/d6/36252ff3d6a0bfaa3fa54e025d671df949b265b426429e7e8ab0149e65c2/timerit-1.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-08-13 22:58:32",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Erotemic",
    "github_project": "timerit",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "appveyor": true,
    "requirements": [],
    "lcname": "timerit"
}
        
Elapsed time: 0.09380s