├── .editorconfig ├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ └── pytest.yml ├── .gitignore ├── .pre-commit-config.yaml ├── LICENSE ├── README.md ├── pyproject.toml ├── pytest_execution_timer ├── __init__.py └── plugin.py └── tests ├── __init__.py ├── conftest.py └── test_pytest_execution_timer.py /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | end_of_line = lf 10 | charset = utf-8 11 | 12 | [*.py] 13 | indent_size = 4 14 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: miketheman 4 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/.github/workflows" 5 | schedule: 6 | interval: "weekly" 7 | -------------------------------------------------------------------------------- /.github/workflows/pytest.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Python Tests 5 | 6 | on: 7 | # Trigger the workflow on push or pull request, 8 | # but only for the main branch 9 | push: 10 | branches: 11 | - main 12 | pull_request: 13 | branches: 14 | - main 15 | 16 | jobs: 17 | build: 18 | 19 | runs-on: ${{ matrix.os }} 20 | strategy: 21 | matrix: 22 | os: 23 | - macos-latest 24 | - ubuntu-latest 25 | - windows-latest 26 | python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] 27 | 28 | steps: 29 | - uses: actions/checkout@v4 30 | - name: Set up Python ${{ matrix.python-version }} 31 | uses: actions/setup-python@v5 32 | with: 33 | python-version: ${{ matrix.python-version }} 34 | - name: Install dependencies 35 | run: | 36 | python -m pip install --upgrade pip poetry 37 | poetry install 38 | - name: Test with coverage/pytest 39 | run: | 40 | poetry run coverage run -m pytest ; poetry run coverage report --show-missing 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | poetry.lock 103 | 104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 105 | __pypackages__/ 106 | 107 | # Celery stuff 108 | celerybeat-schedule 109 | celerybeat.pid 110 | 111 | # SageMath parsed files 112 | *.sage.py 113 | 114 | # Environments 115 | .env 116 | .envrc 117 | .venv 118 | env/ 119 | venv/ 120 | ENV/ 121 | env.bak/ 122 | venv.bak/ 123 | 124 | # Spyder project settings 125 | .spyderproject 126 | .spyproject 127 | 128 | # Rope project settings 129 | .ropeproject 130 | 131 | # mkdocs documentation 132 | /site 133 | 134 | # mypy 135 | .mypy_cache/ 136 | .dmypy.json 137 | dmypy.json 138 | 139 | # Pyre type checker 140 | .pyre/ 141 | 142 | # pytype static type analyzer 143 | .pytype/ 144 | 145 | # Cython debug symbols 146 | cython_debug/ 147 | 148 | # PyCharm 149 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 150 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 151 | # and can be added to the global gitignore or merged into this file. For a more nuclear 152 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 153 | .idea/ 154 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v5.0.0 6 | hooks: 7 | - id: check-yaml 8 | - id: check-added-large-files 9 | - repo: https://github.com/editorconfig-checker/editorconfig-checker.python 10 | rev: '3.2.1' 11 | hooks: 12 | - id: editorconfig-checker 13 | alias: ec 14 | - repo: https://github.com/pycqa/isort 15 | rev: 6.0.1 16 | hooks: 17 | - id: isort 18 | name: isort (python) 19 | - repo: https://github.com/psf/black 20 | rev: 25.1.0 21 | hooks: 22 | - id: black 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | The MIT License (MIT) 3 | 4 | Copyright (c) 2021 Mike Fiedler 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in 14 | all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pytest-execution-timer 2 | 3 | [![PyPI current version](https://img.shields.io/pypi/v/pytest-execution-timer.svg)](https://pypi.python.org/pypi/pytest-execution-timer) 4 | [![Python Support](https://img.shields.io/pypi/pyversions/pytest-execution-timer.svg)](https://pypi.python.org/pypi/pytest-execution-timer) 5 | [![Tests](https://github.com/miketheman/pytest-execution-timer/workflows/Python%20Tests/badge.svg)](https://github.com/miketheman/pytest-execution-timer/actions?query=workflow%3A%22Python+Tests%22) 6 | [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/miketheman/pytest-execution-timer/main.svg)](https://results.pre-commit.ci/latest/github/miketheman/pytest-execution-timer/main) 7 | [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) 8 | 9 | A plugin to use with Pytest to measure execution time of tests. 10 | 11 | Distinctly different from the `--durations` option of pytest, 12 | this plugin measures specific pytest startup/collection phases. 13 | 14 | Leverages `pytest` hooks to measure execution time of phases. 15 | 16 | --- 17 | 18 | ## Installation 19 | 20 | Requires: 21 | 22 | - Python 3.8 or later. 23 | - Pytest 6.2 or later. 24 | 25 | Install the plugin with any approach for your project. 26 | 27 | Some examples: 28 | 29 | ```shell 30 | pip install pytest-execution-timer 31 | ``` 32 | 33 | ```shell 34 | poetry add --dev pytest-execution-timer 35 | ``` 36 | 37 | ```shell 38 | pipenv install --dev pytest-execution-timer 39 | ``` 40 | 41 | Or add it to your `requirements.txt` file. 42 | 43 | ## Usage 44 | 45 | Enable the plugin with the `--execution-timer` option when running `pytest`: 46 | 47 | ```console 48 | $ pytest --execution-timer 49 | ... 50 | Durations of pytest phases in seconds (min 100ms): 51 | 0.662 pytest_runtestloop 52 | ``` 53 | 54 | Control the threshold (default 100ms) by passing `--minimum-duration=`: 55 | 56 | ```console 57 | $ pytest --execution-timer --minimum-duration=1000 # 1 second 58 | ``` 59 | 60 | ## Understanding the output 61 | 62 | The best ay to start is to compare the difference of the `pytest_runtestloop` duration 63 | and the overall duration of the test run. Example: 64 | 65 | ```console 66 | Durations of pytest phases in seconds (min 100ms): 67 | 0.666 pytest_runtestloop 68 | ====== 4 passed in 0.68s ====== 69 | ``` 70 | 71 | In this example, there's not much lost between the test run and the `pytest_runtestloop` 72 | meaning that the startup and collection phases are not taking too much time. 73 | 74 | If there's a larger difference in the timings, 75 | look to other emitted phases to understand what's taking the most time. 76 | 77 | These can then be examined directly, 78 | or use other tools like [profilers](https://docs.python.org/3/library/profile.html) 79 | or [import timings](https://docs.python.org/3/using/cmdline.html#cmdoption-X). 80 | 81 | ## License 82 | 83 | Distributed under the terms of the MIT license, 84 | "pytest-execution-timer" is free and open source software. 85 | See `LICENSE` for more information. 86 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "pytest-execution-timer" 3 | version = "0.1.0" 4 | description = "A timer for the phases of Pytest's execution." 5 | authors = ["Mike Fiedler "] 6 | license = "MIT" 7 | readme = "README.md" 8 | homepage = "https://pypi.org/project/pytest-execution-timer/" 9 | repository = "https://github.com/miketheman/pytest-execution-timer" 10 | include = [ 11 | { path = "LICENSE" }, 12 | { path = "README.md" }, 13 | { path = "tests", format = "sdist" }, 14 | ] 15 | classifiers = [ 16 | "Development Status :: 4 - Beta", 17 | "Framework :: Pytest", 18 | "Intended Audience :: Developers", 19 | "Topic :: Software Development :: Testing", 20 | "Programming Language :: Python", 21 | "Programming Language :: Python :: 3.8", 22 | "Programming Language :: Python :: 3.9", 23 | "Programming Language :: Python :: 3.10", 24 | "Programming Language :: Python :: 3.11", 25 | "Programming Language :: Python :: 3.12", 26 | "Programming Language :: Python :: Implementation :: CPython", 27 | "Operating System :: OS Independent", 28 | "License :: OSI Approved :: MIT License", 29 | ] 30 | 31 | 32 | [tool.poetry.dependencies] 33 | python = "^3.8" 34 | 35 | [tool.poetry.dev-dependencies] 36 | pytest = "^6.2" 37 | coverage = {extras = ["toml"], version = "^6.2"} 38 | 39 | [tool.poetry.plugins.pytest11] 40 | execution_timer = "pytest_execution_timer.plugin" 41 | 42 | [tool.poetry.urls] 43 | "Bug Tracker" = "https://github.com/miketheman/pytest-execution-timer/issues" 44 | 45 | [tool.coverage.run] 46 | branch = true 47 | source = ["pytest_execution_timer"] 48 | 49 | [tool.isort] 50 | # https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html#profilegcm 51 | profile = "black" 52 | 53 | [build-system] 54 | requires = ["poetry-core>=1.0.0"] 55 | build-backend = "poetry.core.masonry.api" 56 | -------------------------------------------------------------------------------- /pytest_execution_timer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miketheman/pytest-execution-timer/f1ff406127c16e7102f881a6c3783101feffa275/pytest_execution_timer/__init__.py -------------------------------------------------------------------------------- /pytest_execution_timer/plugin.py: -------------------------------------------------------------------------------- 1 | import time 2 | import typing 3 | from datetime import timedelta 4 | 5 | import pytest 6 | 7 | 8 | class PytestExecutionTimer: 9 | """ 10 | A timer for the phases of Pytest's execution. 11 | Distinctly different from `--durations=N` 12 | in that this reports times spent **outside** tests. 13 | 14 | Not every hook is instrumented yet, 15 | only the ones that I've observed causing slowdown. 16 | More hook contributions are welcome! 17 | """ 18 | 19 | durations: typing.Dict[str, float] = dict() 20 | 21 | # === Initialization Hooks === 22 | # https://docs.pytest.org/en/stable/reference.html#initialization-hooks 23 | @pytest.hookimpl(hookwrapper=True, tryfirst=True) 24 | def pytest_sessionstart(self, session): 25 | start = time.time() 26 | yield 27 | end = time.time() 28 | self.durations["pytest_sessionstart"] = end - start 29 | 30 | # === Collection Hooks === 31 | # https://docs.pytest.org/en/stable/reference.html#collection-hooks 32 | @pytest.hookimpl(hookwrapper=True, tryfirst=True) 33 | def pytest_collection(self, session): 34 | start = time.time() 35 | yield 36 | end = time.time() 37 | self.durations["pytest_collection"] = end - start 38 | 39 | @pytest.hookimpl(hookwrapper=True, tryfirst=True) 40 | def pytest_collect_file(self, path, parent): 41 | start = time.time() 42 | yield 43 | end = time.time() 44 | self.durations[f"pytest_collect_file:{path}"] = end - start 45 | 46 | @pytest.hookimpl(hookwrapper=True, tryfirst=True) 47 | def pytest_itemcollected(self, item): 48 | start = time.time() 49 | yield 50 | end = time.time() 51 | self.durations[f"pytest_itemcollected\t{item.name}"] = end - start 52 | 53 | # === Run Test Hooks === 54 | # https://docs.pytest.org/en/stable/reference.html#test-running-runtest-hooks 55 | @pytest.hookimpl(hookwrapper=True, tryfirst=True) 56 | def pytest_runtestloop(self, session): 57 | """Should mimic the output of the total test time reported by pytest. 58 | May not be necessary.""" 59 | start = time.time() 60 | yield 61 | end = time.time() 62 | self.durations["pytest_runtestloop"] = end - start 63 | 64 | # === Reporting Hooks === 65 | # https://docs.pytest.org/en/stable/reference.html#reporting-hooks 66 | @pytest.hookimpl(hookwrapper=True, tryfirst=True) 67 | def pytest_make_collect_report(self, collector): 68 | """Despite being a Reporting hook, this fires during the Collection phase 69 | and can find `test_*.py` level import slowdowns.""" 70 | start = time.time() 71 | yield 72 | end = time.time() 73 | self.durations[f"pytest_make_collect_report\t{collector.nodeid}"] = end - start 74 | 75 | def pytest_terminal_summary(self, terminalreporter, exitstatus, config): 76 | """Where we emit our report.""" 77 | min_duration = config.option.minimum_duration_in_ms 78 | 79 | terminalreporter.section("pytest-execution-timer") 80 | terminalreporter.write_line( 81 | f"Durations of pytest phases in seconds (min {min_duration}ms):" 82 | ) 83 | 84 | for key, value in self.durations.items(): 85 | # Only show items that took longer than the configured value 86 | if value > timedelta(milliseconds=min_duration).total_seconds(): 87 | terminalreporter.write_line(f"{value:.3f}\t{key}") 88 | 89 | 90 | def pytest_addoption(parser): 91 | group = parser.getgroup("execution_timer") 92 | group.addoption( 93 | "--execution-timer", 94 | action="store_true", 95 | dest="execution_timer", 96 | help="Enable collection of pytest phase execution timing.", 97 | ) 98 | group.addoption( 99 | "--minimum-duration", 100 | action="store", 101 | dest="minimum_duration_in_ms", 102 | type=int, 103 | default=100, 104 | help="Minimum duration in milliseconds to show in the report.", 105 | ) 106 | 107 | 108 | def pytest_configure(config): 109 | if config.option.execution_timer: 110 | config.pluginmanager.register(PytestExecutionTimer()) 111 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/miketheman/pytest-execution-timer/f1ff406127c16e7102f881a6c3783101feffa275/tests/__init__.py -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | pytest_plugins = "pytester" 2 | -------------------------------------------------------------------------------- /tests/test_pytest_execution_timer.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | def test_shows_help_when_enabled(pytester): 5 | result = pytester.runpytest("--help") 6 | assert result.ret == 0 7 | result.stdout.fnmatch_lines( 8 | ["*execution_timer:*", "*--execution-timer*", "*--minimum-duration*"] 9 | ) 10 | 11 | 12 | def test_does_not_emit_when_not_enabled(pytester): 13 | pytester.makepyfile( 14 | """ 15 | import time 16 | 17 | def test_execution(): 18 | time.sleep(0.2) 19 | """ 20 | ) 21 | result = pytester.runpytest() 22 | assert result.ret == 0 23 | # Confirm that the plugin output is not present 24 | with pytest.raises(pytest.fail.Exception): 25 | result.stdout.fnmatch_lines(["*Durations*", "*0.*pytest_runtestloop*"]) 26 | 27 | 28 | def test_omits_duration_when_enabled(pytester): 29 | pytester.makepyfile( 30 | """ 31 | import time 32 | 33 | def test_execution(): 34 | time.sleep(0.2) 35 | """ 36 | ) 37 | result = pytester.runpytest("--execution-timer") 38 | assert result.ret == 0 39 | result.stdout.fnmatch_lines(["*Durations*", "*0.*pytest_runtestloop*"]) 40 | 41 | 42 | def test_configured_duration_is_used(pytester): 43 | pytester.makepyfile( 44 | """ 45 | import time 46 | 47 | def test_execution(): 48 | time.sleep(0.1) 49 | """ 50 | ) 51 | result = pytester.runpytest("--execution-timer", "--minimum-duration=100") 52 | assert result.ret == 0 53 | result.stdout.fnmatch_lines(["*Durations*", "*0.*pytest_runtestloop*"]) 54 | --------------------------------------------------------------------------------