Skip to content

profiling.sampling: Statistical Profiler in the Standard Library

profiling.sampling is the statistical sampling profiler that ships with Python 3.15, developed under the codename Tachyon. It samples the call stacks of a Python process on a timer rather than instrumenting every call, and it can attach to a process that is already running by PID. The CLI is invoked as python -m profiling.sampling, with run and attach as the two profiling entry points, dump for a single stack snapshot, and replay for converting saved binary profiles to other output formats.

The package structure follows PEP 799, a dedicated profiling package. profiling.tracing provides deterministic profiling, and cProfile remains a compatible alias.

Check availability

profiling.sampling requires Python 3.15 or later.

uv installs the latest available patch for a minor version:

uv python install 3.15

The command reports an installed Python executable, or that the requested interpreter is already installed. The version compatibility requirements apply when attaching to an existing process.

When to use profiling.sampling

Reach for profiling.sampling when a Python process is running in production or in a long-running development session and a stack profile is needed without restarting it. The profiler attaches to a PID, runs out of process, and produces flame graphs, pstats output, or live terminal stats. It supersedes much of what required a third-party install before 3.15 (see py-spy and pyinstrument), although the third-party tools still cover Python versions before 3.15 and offer different native-stack and memory measurements.

For tool selection across CPU, memory, and async investigations, see Which Python profiler should I use?.

For exact call counts, use profiling.tracing. Sampling also supports line-level heatmaps, although their timings remain estimates. The trade-offs between the two designs are covered in Sampling vs deterministic profilers.

Select a subcommand

The CLI is invoked as python -m profiling.sampling <subcommand>:

Subcommand Purpose
run Launch a Python script or module and profile it from startup
attach Attach to a running process by PID and profile until duration elapses
dump Take a single snapshot of a running process’s call stack
replay Convert a previously recorded binary profile to another output format

Configure sampling

The default sampling rate is 1 kHz. The documented maximum is 1 MHz.

  • -r, --sampling-rate accepts a number or a unit suffix (10000, 10khz, 10k)
  • -d, --duration runs for a fixed number of seconds; default is until the target completes
  • -a, --all-threads samples every thread instead of only the main thread
  • --realtime-stats prints sampling statistics during the run
  • --blocking pauses the target during each sample for a guaranteed-consistent stack at the cost of perturbing the program

Select a profiling mode

--mode selects what each sample counts:

Mode What it measures
wall (default) Wall-clock time; every sample counts regardless of thread state
cpu On-CPU time only; samples taken while a thread is running on a core
gil GIL-holding time; samples taken only while the thread holds the GIL
exception Exception-handling time; samples taken only while an exception is in flight

Wall-clock mode includes time spent blocked on I/O or await. CPU mode excludes it. GIL mode is useful when diagnosing contention in multithreaded programs.

Inspect async tasks and native boundaries

  • --async-aware reconstructs asyncio task stacks across await boundaries; --async-mode running shows only the running task and --async-mode all includes waiting tasks
  • --native inserts synthetic <native> markers where Python calls into native code; it does not unwind native stacks or identify individual C/C++ functions
  • --no-gc excludes <GC> frames so garbage collection time does not dominate the report
  • --opcodes records bytecode opcode information for instruction-level profiling
  • --subprocesses follows multiprocessing and subprocess children automatically

Async-aware mode cannot be combined with --native, --no-gc, --all-threads, --binary, or any sampling mode other than wall. For named native functions, use Austin or py-spy on a supported platform.

Choose an output format

Output formats are mutually exclusive flags:

Flag Output Viewer
--pstats (default) Text table to stdout, or a binary .pstats file pstats module, IDE viewers
--collapsed Semicolon-separated stacks External flame-graph tools (e.g. Brendan Gregg’s scripts)
--flamegraph Self-contained interactive HTML Any browser
--diff-flamegraph BASELINE.bin Differential HTML flame graph Any browser; color-codes regressions vs. a baseline binary
--gecko Gecko-format JSON Firefox Profiler
--heatmap HTML directory with line-level overlays Any browser
--binary Compact binary; supports zstd compression Use with replay to convert later

-o/--output selects the output path, --browser auto-opens HTML output, and --compression {auto,zstd,none} controls the binary format.

The --live flag (available on both run and attach) opens a top-style terminal interface with sortable columns, a substring filter (/), per-thread navigation, and adjustable refresh rate.

Check process permissions

Sampling another process requires OS-level memory inspection, which has the same constraints as py-spy:

  • Linux: ptrace capability, or root, or relax kernel.yama.ptrace_scope
  • macOS: root, or a binary signed with the com.apple.security.cs.debugger entitlement
  • Windows: administrator, or SeDebugPrivilege

Permissions depend on OS policy and process ownership. Linux commonly permits profiling a launched child without elevation. On macOS, root access or the debugger entitlement is required for both launching and attaching.

Match the interpreter and build type

The profiler must run on the same Python minor version as the target process. Pre-release builds must match exactly: 3.15.0a6 profiling 3.15.0a5 will fail. This is stricter than third-party profilers like py-spy that read process memory through OS APIs and support a range of CPython versions from a single profiler binary.

The build type must also match: a free-threaded profiler cannot attach to a standard build, or vice versa.

Use the built-in sampler

  • Ships in the standard library; no pip install and no separate binary.
  • Async-aware sampling reconstructs task stacks across await boundaries.
  • Output formats include HTML flame graphs, Gecko JSON for the Firefox Profiler, line-level heatmaps, and differential flame graphs against a saved baseline.
  • Live terminal mode is built in.

Account for compatibility and viewing limits

  • Available only in Python 3.15 and newer. Older Pythons keep needing third-party tools.
  • Profiler and target must share a Python minor version and build type; pre-release versions must match exactly.
  • On macOS, launching and attaching both require root access or the debugger entitlement.
  • OS process-inspection policies apply: ptrace restrictions on Linux and administrative privileges or SeDebugPrivilege on Windows.
  • Heatmaps and differential flame graphs use the built-in HTML viewer. Gecko and collapsed-stack output serve external viewers; select the format the destination viewer accepts.
Last updated on