|
| 1 | +.. SPDX-FileCopyrightText: 2026 Veit Schiele |
| 2 | +.. |
| 3 | +.. SPDX-License-Identifier: BSD-3-Clause |
| 4 | +
|
| 5 | +``tprof`` |
| 6 | +========= |
| 7 | + |
| 8 | +`tprof <https://github.com/adamchainz/tprof>`_ measures from Python 3.12 onwards |
| 9 | +the time spent executing a module in specific functions. Unlike other profilers, |
| 10 | +it only tracks the specified functions with :mod:`sys.monitoring`, eliminating |
| 11 | +the need for filtering. |
| 12 | + |
| 13 | +``tprof`` supports use as a command line programme and with a Python interface: |
| 14 | + |
| 15 | +:samp:`uv run tprof -t {MODULE}:{FUNCTION} (-m {MODULE} | {PATH/TO/SCRIPT})` |
| 16 | + Suppose you have determined that creating :class:`pathlib.Path` objects in |
| 17 | + the :mod:`main` module is slowing down your code. Here’s how you can measure |
| 18 | + this with ``tprof``: |
| 19 | + |
| 20 | + .. code-block:: console |
| 21 | +
|
| 22 | + $ uv run tprof -t pathlib:Path.open -m main |
| 23 | + 🎯 tprof results: |
| 24 | + function calls total mean ± σ min … max |
| 25 | + pathlib:Path.open() 1 93μs 93μs 93μs … 93μs |
| 26 | +
|
| 27 | + With the ``-x`` option, you can also compare two functions with each other: |
| 28 | + |
| 29 | + .. code-block:: console |
| 30 | +
|
| 31 | + $ uv run tprof -x -t old -m main -t new -m main |
| 32 | + 🎯 tprof results: |
| 33 | + function calls total mean ± σ min … max delta |
| 34 | + main:old() 1 41μs 41μs 41μs … 41μs - |
| 35 | + main:new() 1 20μs 20μs 20μs … 20μs -50.67% |
| 36 | +
|
| 37 | +``tprof(*targets, label: str | None = None, compare: bool = False)`` |
| 38 | + uses this code as a :doc:`context manager <python-basics:control-flow/with>` |
| 39 | + in your code to perform profiling in a specific block. The report is |
| 40 | + generated each time the block is run through. |
| 41 | + |
| 42 | + ``*targets`` |
| 43 | + are callable elements for profiling or references to elements that are |
| 44 | + resolved with :func:`pkgutil.resolve_name`. |
| 45 | + ``label`` |
| 46 | + is an optional string that can be added to the report as a header. |
| 47 | + ``compare`` |
| 48 | + set to ``True`` activates comparison mode. |
| 49 | + |
| 50 | + Example: |
| 51 | + |
| 52 | + .. code-block:: Python |
| 53 | +
|
| 54 | + from pathlib import Path |
| 55 | +
|
| 56 | + from tprof import tprof |
| 57 | +
|
| 58 | + with tprof(Path.open): |
| 59 | + p = Path("docs", "save-data", "myfile.txt") |
| 60 | + f = p.open() |
| 61 | +
|
| 62 | + .. code-block:: console |
| 63 | +
|
| 64 | + $ uv run python main.py |
| 65 | + 🎯 tprof results: |
| 66 | + function calls total mean ± σ min … max |
| 67 | + pathlib:Path.open() 1 82μs 82μs 82μs … 82μs |
0 commit comments