# Python profiling libraries

Python profiling libraries measure where a program spends its time or memory, down to the function or line. A sampling profiler records the call stack at intervals rather than timing every function call. These libraries let developers find the code that slows down a service or exhausts its memory.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [py-spy](#py-spy) | 21.3M | 15.7K | Nov 2026 | MIT |
| [Memray](#memray) | 10.9M | 15.4K | Aug 2026 | Apache-2.0 |
| [Pyinstrument](#pyinstrument) | 9.5M | 8.0K | Jul 2026 | BSD-3-Clause |
| [memory_profiler](#memory-profiler) | 5.4M | 4.6K | Nov 2022 | BSD |
| [Yappi](#yappi) | 3.0M | 1.7K | Mar 2026 | MIT |
| [line_profiler](#line-profiler-library) | 2.1M | 3.3K | Oct 2026 | BSD-3-Clause |
| [VizTracer](#viztracer) | 1.5M | 7.8K | Nov 2025 | Apache-2.0 |
| [Scalene](#scalene) | 293.0K | 13.6K | Oct 2026 | Apache-2.0 |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[py-spy](#py-spy) has the most monthly downloads in this comparison, at 21.3M.

## Capabilities

| Library | Python API | Execution timing | Memory profiling |
| --- | --- | --- | --- |
| [py-spy](#py-spy) | No | Yes | No |
| [Memray](#memray) | Yes | No | Yes |
| [Pyinstrument](#pyinstrument) | Yes | Yes | No |
| [memory_profiler](#memory-profiler) | Yes | No | Yes |
| [Yappi](#yappi) | Yes | Yes | No |
| [line_profiler](#line-profiler-library) | Yes | Yes | No |
| [VizTracer](#viztracer) | Yes | Yes | No |
| [Scalene](#scalene) | Yes | Yes | Yes |

## Libraries

### py-spy

[GitHub](https://github.com/benfred/py-spy) · [PyPI](https://pypi.org/project/py-spy) · [Docs](https://github.com/benfred/py-spy/blob/master/README.md)

Samples Python programs to profile them.

- Downloads / mo: 21.3M
- Stars: 15.7K
- Last release: 0.4.3
- License: MIT
- Capabilities: [From the py-spy docs](https://github.com/benfred/py-spy/blob/master/README.md)

```sh
python -m pip install py-spy==0.4.3
```

**xai-org/x-algorithm** (34.3K stars)

[xai-org/x-algorithm](https://github.com/xai-org/x-algorithm) 

```python
def start_pyspy_trace(dir_path: os.PathLike, blocking: bool = False, rate: int = 100) -> None:
    with _pyspy_state.lock:
        if _pyspy_state.process is not None:
            raise RuntimeError("Only one py-spy profile may be run at a time.")

        timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
        pid = os.getpid()
        output_path = Path(dir_path) / f"{pid}-{timestamp}.json"
        output_path.parent.mkdir(parents=True, exist_ok=True)
        logger.info(f"Profiling to {output_path}...")

        cmd = [
            "py-spy",
            "record",
            "--pid",
            str(pid),
            "--format",
            "speedscope",
            "--nonblocking" if not blocking else "--native",
            "--rate",
            f"{rate}",
            "-o",
            str(output_path),
        ]

        env = os.environ.copy()
        env["RUST_LOG"] = "warn"

        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
        _pyspy_state.process = process

```

[phoenix/xrex/utils/pyspy_profiler.py](https://github.com/xai-org/x-algorithm/blob/b55151777cd8901111c7b5985a724f671f05d2c4/phoenix/xrex/utils/pyspy_profiler.py#L27-L56) · [More projects using py-spy →](https://dashboard.exa.ai/playground/search?q=py-spy%20GitHub%20projects)

**Quickstart**

```python
py-spy record -o profile.svg -- python your_script.py

```

From [README.md](https://github.com/benfred/py-spy/blob/master/README.md)

### Memray

[GitHub](https://github.com/bloomberg/memray) · [PyPI](https://pypi.org/project/memray) · [Docs](https://github.com/bloomberg/memray/blob/main/README.md)

Profiles memory in Python applications.

- Downloads / mo: 10.9M
- Stars: 15.4K
- Last release: 1.20.0
- License: Apache-2.0
- Capabilities: [From the Memray docs](https://github.com/bloomberg/memray/blob/main/README.md)

```sh
python -m pip install memray==1.20.0
```

**bloomberg/pytest-memray** (428 stars)

[bloomberg/pytest-memray](https://github.com/bloomberg/pytest-memray) 

```python
@contextmanager
def memory_reporting() -> Generator[Tuple[Tracker, bool], None, None]:
    # Restore the original function. This is needed because some
    # pytest plugins (e.g. flaky) will call our pytest_pyfunc_call
    # hook again with whatever is here, which will cause the wrapper
    # to be wrapped again.
    pyfuncitem.obj = func

    result_file = _build_bin_path()
    tracker_kwargs = {
        "native_traces": native,
        "trace_python_allocators": trace_python_allocators,
        "file_format": FileFormat.AGGREGATED_ALLOCATIONS,
    }

    # Add track_object_lifetimes if tracking objects
    if track_objects:  # pragma: no cover
        tracker_kwargs["track_object_lifetimes"] = True

    # mypy can't resolve the overload when using **kwargs unpacking
    tracker = Tracker(result_file, **tracker_kwargs)  # type: ignore[call-overload]
    yield (tracker, track_objects)

    # Get surviving objects if tracking was enabled
    surviving_objects = None
    if track_objects:  # pragma: no cover
        surviving_objects = list(tracker.get_surviving_objects())

    try:
        metadata = FileReader(result_file).metadata
    except OSError:
        return
    result = Result(pyfuncitem.nodeid, metadata.peak_memory, result_file)

    with NamedTemporaryFile(
        dir=self.result_metadata_path,
        delete=False,
    ) as tmp_file:
        tmp_file.write(
            json.dumps(
                {
                    "test_id": result.test_id,
                    "peak_memory": result.peak_memory,
                    "result_file": str(result.result_file),
                }
            ).encode("utf-8")
        )

    metadata_filename = result_file.with_suffix(".metadata").name
    os.replace(tmp_file.name, self.result_metadata_path / metadata_filename)

    self.results[pyfuncitem.nodeid] = result

    # Store surviving objects separately (they can't be serialized)
    if surviving_objects is not None:  # pragma: no cover
        self.surviving_objects[pyfuncitem.nodeid] = surviving_objects

```

[src/pytest_memray/plugin.py](https://github.com/bloomberg/pytest-memray/blob/e1f35e2a1aa7c6d4a6a485a90bdae245efaff942/src/pytest_memray/plugin.py#L230-L285) · [More projects using Memray →](https://dashboard.exa.ai/playground/search?q=memray%20GitHub%20projects)

**Quickstart**

```python
import memray

with memray.Tracker("profile.bin"):
    values = [i * i for i in range(10000)]

```

From [api.rst](https://bloomberg.github.io/memray/api.html)

### Pyinstrument

[GitHub](https://github.com/joerick/pyinstrument) · [PyPI](https://pypi.org/project/pyinstrument) · [Docs](https://github.com/joerick/pyinstrument/blob/main/README.md)

Samples Python call stacks to explain elapsed time across nested application work.

- Downloads / mo: 9.5M
- Stars: 8.0K
- Last release: 5.1.3
- License: BSD-3-Clause
- Capabilities: [From the Pyinstrument docs](https://github.com/joerick/pyinstrument/blob/main/README.md)

**Strengths**

- **Shows the full call stack.** Trace elapsed time through callers and nested function work.
- **Renders browser-readable reports.** Export HTML or JSON reports through its renderer interface.

**Watch out for**

- **Elapsed time includes I/O waits.** Waiting for network, files, or databases contributes to reported duration.
- **Sampling omits exact call counts.** Sampled stacks describe elapsed activity rather than every function invocation.

```sh
python -m pip install pyinstrument==5.1.3
```

**treeverse/dvc** (16.0K stars)

[treeverse/dvc](https://github.com/treeverse/dvc) 

```python
@contextmanager
def instrument(html_output=False):
    """Run a statistical profiler"""
    try:
        from pyinstrument import Profiler  # ty: ignore[unresolved-import]
    except ImportError:
        print("Failed to run profiler, pyinstrument is not installed")  # noqa: T201
        yield
        return

    profiler = Profiler()

    profiler.start()
    try:
        yield
    finally:
        profiler.stop()

        if html_output:
            profiler.open_in_browser()
        else:
            print(profiler.output_text(unicode=True, color=True))  # noqa: T201

```

[dvc/_debug.py](https://github.com/treeverse/dvc/blob/b59add99ee667f2b352cc1be337619f965fe3fea/dvc/_debug.py#L78-L99) · [More projects using Pyinstrument →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20pyinstrument%20for%20profiler%20lifecycle%20control%2C%20merged%20sessions%2C%20clock%20selection%20and%20source-line%20registration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**holoviz/panel** (5.8K stars)

[holoviz/panel](https://github.com/holoviz/panel) 

```python
def render_pyinstrument(sessions, timeline=False, show_all=False):
    from pyinstrument.renderers import HTMLRenderer
    from pyinstrument.session import Session
    r = HTMLRenderer(timeline=timeline, show_all=show_all)
    if timeline:
        session = sessions[-1]
    else:
        session = sessions[0]
        for s in sessions[1:]:
            session = Session.combine(session, s)
    try:
        rendered = r.render(session)
    except Exception:
        rendered = "<h2><b>Rendering pyinstrument session failed</b></h2>"
    return escape(rendered), ""

```

[panel/io/profile.py](https://github.com/holoviz/panel/blob/ea4f3836f84b11864638a7c951f4db84d7049f61/panel/io/profile.py#L29-L43) · [More projects using Pyinstrument →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20pyinstrument%20for%20profiler%20lifecycle%20control%2C%20merged%20sessions%2C%20clock%20selection%20and%20source-line%20registration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from pyinstrument import Profiler
import time

profiler = Profiler()
profiler.start()
time.sleep(0.05)
profiler.stop()
print(profiler.output_text())

```

From [guide.html](https://github.com/joerick/pyinstrument/blob/main/README.md)

### memory_profiler

[GitHub](https://github.com/pythonprofilers/memory_profiler) · [PyPI](https://pypi.org/project/memory-profiler) · [Docs](https://github.com/pythonprofilers/memory_profiler/blob/master/README.rst)

Monitors the memory usage of a Python program.

- Downloads / mo: 5.4M
- Stars: 4.6K
- Last release: 0.61.0
- License: BSD
- Capabilities: [From the memory_profiler docs](https://github.com/pythonprofilers/memory_profiler/blob/master/README.rst)

```sh
python -m pip install memory-profiler==0.61.0
```

**facebookresearch/fairseq** (32.2K stars)

[facebookresearch/fairseq](https://github.com/facebookresearch/fairseq) 

```python
def max_memory(self, dataset, repeat):
    """Compute average max memory consumed by model inference. Units are MiB"""
    logger.info("Starting memory benchmarking")
    total_memory = 0
    for i, sample in enumerate(dataset):
        for _r in range(repeat):
            total_memory += max(memory_usage((self.forward, (sample,), {})))
        if i % 100 == 0:
            logger.info(f"Benchmarked memory for {i}/{len(dataset)} samples")
    total_memory = total_memory / (repeat * len(dataset))
    return total_memory

```

[examples/speech_to_speech/benchmarking/core.py](https://github.com/facebookresearch/fairseq/blob/3d262bb25690e4eb2e7d3c1309b1e9c406ca4b99/examples/speech_to_speech/benchmarking/core.py#L75-L85) · [More projects using memory_profiler →](https://dashboard.exa.ai/playground/search?q=memory-profiler%20GitHub%20projects)

**Quickstart**

```python
from memory_profiler import memory_usage

print(memory_usage(-1, interval=0.1, timeout=0.2))

```

From [memory_profiler.py](https://raw.githubusercontent.com/pythonprofilers/memory_profiler/master/memory_profiler.py)

### Yappi

[GitHub](https://github.com/sumerc/yappi) · [PyPI](https://pypi.org/project/yappi) · [Docs](https://github.com/sumerc/yappi/blob/master/README.md)

Traces Python function calls with CPU or wall clocks and thread-aware profiling statistics.

- Downloads / mo: 3.0M
- Stars: 1.7K
- Last release: 1.7.6
- License: MIT
- Capabilities: [From the Yappi docs](https://github.com/sumerc/yappi/blob/master/README.md)

**Strengths**

- **Chooses CPU or wall time.** Switch clocks to separate CPU consumption from elapsed waiting.
- **Separates work by thread.** Filter function statistics by thread context identifiers.

**Watch out for**

- **CPU timing omits blocked waits.** Choose wall time when blocked I/O belongs in the measurement.
- **Results persist until explicitly cleared.** Call yappi.clear_stats between independent profiling sessions.

```sh
python -m pip install yappi==1.7.6
```

**oVirt/vdsm** (193 stars)

[oVirt/vdsm](https://github.com/oVirt/vdsm) 

```python
def stop(self):
    if not yappi.is_running():
        raise UsageError("CPU profiler is not running")

    logging.info("Stopping CPU profiling")
    yappi.stop()
    stats = yappi.get_func_stats()
    stats.save(self.filename, self.format)
    yappi.clear_stats()

```

[lib/vdsm/profiling/cpu.py](https://github.com/oVirt/vdsm/blob/ac6a32ec9eeefd9f909acc3017824bff93abe15a/lib/vdsm/profiling/cpu.py#L57-L65) · [More projects using Yappi →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20yappi%20for%20profiler%20lifecycle%20control%2C%20merged%20sessions%2C%20clock%20selection%20and%20source-line%20registration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import yappi

def work():
    return sum(i * i for i in range(10000))

yappi.start()
work()
yappi.stop()
yappi.get_func_stats().print_all()

```

From [README.md](https://github.com/sumerc/yappi/blob/master/README.md)

### line_profiler

[GitHub](https://github.com/pyutils/line_profiler) · [PyPI](https://pypi.org/project/line-profiler) · [Docs](https://github.com/pyutils/line_profiler/blob/main/README.rst)

Profiles code line by line.

- Downloads / mo: 2.1M
- Stars: 3.3K
- Last release: 5.1.0
- License: BSD-3-Clause
- Capabilities: [From the line_profiler docs](https://github.com/pyutils/line_profiler/blob/main/README.rst)

```sh
python -m pip install line-profiler==5.1.0
```

**apache/cassandra** (10.2K stars)

[apache/cassandra](https://github.com/apache/cassandra) 

```python
def profile_on(fcn_names=None):
    if fcn_names and HAS_LINE_PROFILER:
        pr = LineProfiler()
        for fcn_name in fcn_names:
            pr.add_function(fcn_name)
        pr.enable()
        return pr

    pr = cProfile.Profile()
    pr.enable()
    return pr

```

[pylib/cqlshlib/util.py](https://github.com/apache/cassandra/blob/7d7d6b30dbd3c4d87c7dd89de87ab1318977be39/pylib/cqlshlib/util.py#L115-L125) · [More projects using line_profiler →](https://dashboard.exa.ai/playground/search?q=line-profiler%20GitHub%20projects)

**Quickstart**

```python
from line_profiler import LineProfiler

def total():
    return sum(range(10000))

profiler = LineProfiler()
profiler.add_function(total)
profiler.enable()
total()
profiler.disable()
profiler.print_stats()

```

From [line_profiler.py](https://github.com/pyutils/line_profiler/blob/v5.1.0/line_profiler/line_profiler.py)

### VizTracer

[GitHub](https://github.com/gaogaotiantian/viztracer) · [PyPI](https://pypi.org/project/viztracer) · [Docs](https://github.com/gaogaotiantian/viztracer/blob/master/README.md)

Traces and visualizes Python code execution.

- Downloads / mo: 1.5M
- Stars: 7.8K
- Last release: 1.1.1
- License: Apache-2.0
- Capabilities: [From the VizTracer docs](https://github.com/gaogaotiantian/viztracer/blob/master/README.md)

```sh
python -m pip install viztracer==1.1.1
```

**triton-inference-server/pytriton** (849 stars)

[triton-inference-server/pytriton](https://github.com/triton-inference-server/pytriton) 

```python
@classmethod
def _run_server(cls, registry, address, authkey, serializer, writer, initializer=None, initargs=()):
    PR_SET_PDEATHSIG = 1  # noqa
    libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)
    libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM)  # terminate process when parent **thread** dies

    if bool(os.environ.get("PYTRITON_VIZTRACER")):
        from viztracer import VizTracer  # type: ignore # pytype: disable=import-error

        cls._tracer = VizTracer(log_async=True, log_gc=True, tracer_entries=10000000, pid_suffix=True)
        cls._tracer.register_exit()
        cls._tracer.start()

    super()._run_server(
        registry, address, authkey, serializer, writer, initializer, initargs
    )  # pytype: disable=attribute-error

```

[pytriton/proxy/data.py](https://github.com/triton-inference-server/pytriton/blob/88e92b5ec7cfdf8f22d4e9f00671db331f8288dc/pytriton/proxy/data.py#L380-L395) · [More projects using VizTracer →](https://dashboard.exa.ai/playground/search?q=viztracer%20GitHub%20projects)

**Quickstart**

```python
from viztracer import VizTracer

def work():
    return sum(range(10000))

with VizTracer(output_file="trace.json"):
    work()

```

From [README.md](https://github.com/gaogaotiantian/viztracer/blob/master/README.md)

### Scalene

[GitHub](https://github.com/plasma-umass/scalene) · [PyPI](https://pypi.org/project/scalene) · [Docs](https://github.com/plasma-umass/scalene/blob/master/README.md)

Profiles source-line CPU activity and memory allocation, with optional NVIDIA GPU reporting.

- Downloads / mo: 293.0K
- Stars: 13.6K
- Last release: 2.4.0
- License: Apache-2.0
- Capabilities: [From the Scalene docs](https://github.com/plasma-umass/scalene/blob/master/README.md)

**Strengths**

- **Attributes cost to source lines.** Find Python lines responsible for CPU activity and memory growth.
- **Separates Python and native work.** Distinguish Python execution from time spent in native extension code.

**Watch out for**

- **GPU timing needs NVIDIA hardware.** GPU-time reporting is currently limited to NVIDIA-based systems.
- **Memory tests require a relaunch.** Pytest memory mode restarts the session to initialize allocation tracking.

```sh
python -m pip install scalene==2.4.0
```

**Quickstart**

```python
scalene run your_script.py

```

From [README.md](https://github.com/plasma-umass/scalene/blob/master/README.md) · [Find projects using Scalene →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20scalene%20for%20profiler%20lifecycle%20control%2C%20merged%20sessions%2C%20clock%20selection%20and%20source-line%20registration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

## FAQ

### Which Python profiler should I use?

[py-spy](#py-spy) suits profiling a running process without changing its code. [Pyinstrument](#pyinstrument) suits readable call-stack reports from inside the program. [Memray](#memray) suits tracking down memory allocations.

### What is Scalene?

[Scalene](#scalene) samples CPU time, memory, and GPU activity and attributes them to Python and native code.

### What is py-spy?

[py-spy](#py-spy) is a sampling profiler that attaches to a running Python process from outside it. It needs no changes to the application and may require extra permissions to attach.

### What is Memray?

[Memray](#memray) is a memory profiler that tracks allocations from Python, the interpreter, and native code, with the stack that made each one.

### How do I profile memory usage in Python?

[Memray](#memray) records each allocation and the code that made it. [memory_profiler](#memory-profiler) samples memory usage line by line or for a whole process.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python profiling libraries Pyinstrument Yappi line_profiler Scalene code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
