Performance problems in Python applications are not always easy to identify. An application may respond slowly because of expensive calculations, frequent database calls, network delays, background threads, or inefficient code. Without proper profiling, developers often spend time optimizing functions that are not responsible for the actual slowdown.
Python 3.15 introduces Tachyon, a statistical sampling profiler available through the profiling.sampling module. It helps developers understand where an application spends its execution time by periodically collecting stack traces from running processes.
Unlike traditional profiling approaches that instrument every function call, Tachyon observes a running Python process externally. This makes it useful for investigating performance problems without adding profiling code to the application or restarting an existing process.
In this article, you will learn how Tachyon works, how to profile Python scripts and running applications, how to generate flame graphs, and how to use its different profiling modes to investigate real-world performance problems.
What Is the Tachyon Profiler?
Tachyon is a statistical sampling profiler introduced in Python 3.15. It is available through the built-in profiling.sampling module and can profile both newly launched Python programs and processes that are already running.
A sampling profiler periodically captures the call stack of a running application. Each captured stack provides information about the functions that were executing at that moment.
For example, suppose a web application spends a significant amount of time processing database results. If the profiler repeatedly captures stack traces containing the same data-processing function, that function is likely consuming a considerable portion of the application's execution time.
Tachyon uses these samples to estimate where the application spends its time.
Its main capabilities include:
Profiling Python scripts and modules from startup.
Attaching to an existing Python process using its process ID.
Collecting stack traces from multiple threads.
Generating interactive flame graphs and source-code heatmaps.
Monitoring applications through a live terminal interface.
Investigating asynchronous Python applications.
Collecting opcode-level information.
Analyzing CPU time, wall-clock time, GIL-holding time, and exception-handling time.
Tachyon supports sampling rates of up to 1,000,000 Hz. However, the appropriate sampling rate depends on the application, operating system, and available system resources. A higher sampling rate is not automatically better for every profiling session.
How Statistical Sampling Works
Traditional deterministic profilers record function calls and returns as they happen. This provides detailed information, but recording every event introduces overhead into the application.
Tachyon follows a different approach.
Instead of recording every function call, it periodically captures snapshots of the application's call stack. Functions that appear frequently in these snapshots are likely to consume a significant amount of execution time.
Consider an application with three functions:
process_orders()
calculate_discount()
load_customer_data()
If process_orders() appears in many captured stacks, Tachyon can identify it as a frequently active part of the application. The same information can help developers investigate the functions called by process_orders().
The profiler estimates time using the number of samples associated with each function.
For example, suppose a profiling session collects 100,000 samples and a function appears in 5,000 samples. That function represents approximately 5% of the collected samples.
If the profiling session lasted 10 seconds, the estimated time associated with that function would be approximately 500 milliseconds.
This is a statistical estimate, not an exact measurement. Results can vary slightly between profiling sessions.
Sampling Versus Deterministic Profiling
Python 3.15 organizes its profiling tools under the profiling package. It includes profiling.tracing for deterministic tracing and profiling.sampling for statistical sampling.
Feature | Tachyon sampling | Deterministic tracing |
|---|
Measurement approach | Periodically captures stack traces | Records function calls and returns |
Function call counts | Estimated from samples | Exact call counts |
Application instrumentation | Not required | Uses tracing instrumentation |
Profiling overhead | Generally low | Can be higher |
Short-lived functions | May be missed | Captured when tracing is active |
Production investigation | Useful for low-overhead observation | May introduce additional overhead |
Best use case | Finding performance hotspots | Detailed function-level analysis |
Use Tachyon when you want to understand where an application spends time. Use deterministic tracing when you need exact function call counts or more detailed call-level measurements.
Requirements for Using Tachyon
Tachyon is introduced in Python 3.15. Make sure the Python interpreter used for profiling supports this module.
Check the installed Python version:
python --version
The output should indicate Python 3.15.
You can also verify that the sampling profiler is available:
python -m profiling.sampling --help
Tachyon is part of the Python standard library, so you do not need to install a separate third-party profiling package.
There are also operating-system requirements when attaching to an existing process. Because Tachyon reads the target process's memory to collect stack traces, the operating system may require elevated permissions.
Another important requirement is version compatibility. The profiler and target process must use the same Python minor version. For example, a Python 3.15 profiler cannot attach to a Python 3.14 process.
Profiling a Python Application From Startup
The simplest way to use Tachyon is to launch a Python script through its run command.
Consider the following application.
import time
def load_customers():
time.sleep(1)
return [f"Customer-{i}" for i in range(1000)]
def calculate_total(customers):
total = 0
for customer in customers:
total += len(customer)
return total
def main():
customers = load_customers()
total = calculate_total(customers)
print(f"Processed {len(customers)} customers")
print(f"Total: {total}")
if __name__ == "__main__":
main()
Save the file as app.py.
You can profile the application using:
python -m profiling.sampling run app.py
Tachyon launches the application, waits for it to initialize, and begins collecting samples.
The profiler continues until the application finishes or the profiling session is interrupted.
This approach is useful during development because you do not need to modify the application source code or add profiling decorators.
Profiling a Python Module
Tachyon can also profile an application launched as a Python module.
python -m profiling.sampling run -m mypackage.module
If the module accepts command-line arguments, pass them after the module name:
python -m profiling.sampling run -m mypackage.module --config settings.yaml
This is particularly useful for applications that are normally started through a package entry point or module command.
Attaching to an Existing Python Process
One of Tachyon's useful capabilities is profiling an application that is already running.
This is valuable when a performance problem occurs in a development environment, staging server, or production process that should not be restarted just to collect profiling information.
First, identify the Python process ID.
On Linux or macOS, you can use:
ps aux | grep python
On Windows, use:
Get-Process python
Once you have the process ID, attach Tachyon:
python -m profiling.sampling attach 12345
Replace 12345 with the actual process ID.
You can also limit the profiling session to 30 seconds and save an interactive flame graph:
python -m profiling.sampling attach --flamegraph -d 30 -o profile.html 12345
After collecting the samples, Tachyon detaches from the target process and generates the requested output.
Attaching to an existing process requires appropriate operating-system permissions. It is important to verify these permissions before attempting to profile a production service.
Understanding Profiling Modes
Tachyon supports different profiling modes. Each mode captures a different aspect of application execution.
Choosing the correct mode is important because a function that consumes a lot of elapsed time may not necessarily consume a lot of CPU time.
Wall-Clock Mode
Wall-clock mode is the default profiling mode.
It records samples regardless of whether a thread is executing code, waiting for network activity, blocked on I/O, or sleeping.
Run the profiler using:
python -m profiling.sampling run --mode=wall app.py
Consider a web application that makes several external API requests. A request-handling function may spend most of its time waiting for a response rather than executing Python instructions.
Wall-clock profiling helps identify these waiting periods.
Use this mode when investigating:
CPU Mode
CPU mode records samples only when a thread is actively executing on a CPU core.
python -m profiling.sampling run --mode=cpu app.py
This mode excludes time spent sleeping, waiting for I/O, or waiting for a lock.
It is useful for identifying computational bottlenecks such as expensive calculations, inefficient loops, and CPU-intensive data transformations.
For example, if an application spends a significant amount of time processing large datasets, CPU mode can help identify which functions are consuming the most processing time.
GIL Mode
GIL mode records samples when a thread holds Python's Global Interpreter Lock.
python -m profiling.sampling run --mode=gil app.py
This mode is useful when investigating multi-threaded Python applications.
If one thread frequently holds the GIL while performing Python operations, other threads may have fewer opportunities to execute Python bytecode.
GIL profiling can help developers investigate:
Threads competing for the GIL.
Python code that monopolizes interpreter execution.
Thread scheduling and responsiveness.
Differences between Python execution and native library operations.
GIL profiling is especially useful when a multi-threaded application does not achieve the expected concurrency.
Exception Mode
Exception mode collects samples from threads with an active exception.
python -m profiling.sampling run --mode=exception app.py
It captures execution while an exception is being propagated or while code is executing inside an exception handler with exception information available.
This can help identify expensive exception-handling paths in applications that repeatedly encounter errors.
For example, an application that uses exceptions for frequent control-flow decisions may spend more time handling exceptions than expected.
Exception mode provides a way to investigate that behavior.
Generating Interactive Flame Graphs
A flame graph provides a visual representation of where an application spends its execution time.
It displays function call stacks as nested rectangles. Wider rectangles represent functions that account for more samples.
Tachyon can generate an interactive HTML flame graph.
python -m profiling.sampling run --flamegraph -o profile.html app.py
After profiling completes, open profile.html in a browser.
You can inspect the call hierarchy and identify functions that appear prominently in the profile.
Flame graphs are useful when an application has many functions and nested calls. Instead of reading a long profiling report, developers can visually explore the functions that contribute most to execution time.
For an already-running process, use:
python -m profiling.sampling attach --flamegraph -o profile.html 12345
The same approach works with a specific profiling duration:
python -m profiling.sampling attach --flamegraph -d 60 -o profile.html 12345
Using Heatmaps to Find Expensive Source Lines
Flame graphs help identify expensive functions, but sometimes developers need to investigate the exact source lines responsible for the performance problem.
Tachyon supports heatmap generation through the --heatmap option.
python -m profiling.sampling run --heatmap app.py
The profiler generates an interactive HTML heatmap with sample counts associated with source-code lines.
A source line that receives a large number of samples deserves closer investigation.
For example, if a loop repeatedly performs expensive transformations, the heatmap may help identify the line where the application spends much of its execution time.
Heatmaps are useful for:
Investigating expensive loops.
Finding frequently executed code paths.
Understanding source-level performance hotspots.
Reviewing functions identified through flame graphs.
A heatmap shows where samples were collected. It does not automatically explain why a particular line is slow, so developers should review the surrounding logic before making changes.
Profiling Multiple Threads
Python applications frequently use threads for background work, request processing, and concurrent operations.
By default, Tachyon samples only the main thread.
To include all threads, use the -a or --all-threads option:
python -m profiling.sampling run -a app.py
This provides a broader view of the application's execution.
For example, consider a server with multiple worker threads. Profiling only the main thread may not reveal which worker is performing expensive operations or waiting for a resource.
Profiling all threads can help identify:
Threads consuming significant CPU time.
Threads waiting for locks.
Uneven distribution of work.
Background tasks that affect application responsiveness.
When investigating a multi-threaded application, compare the results with the default main-thread profile to understand how work is distributed.
Profiling Asynchronous Python Applications
Asynchronous applications use await expressions to suspend and resume coroutines. A traditional stack snapshot may not always provide the complete picture of asynchronous execution.
Tachyon provides the --async-aware option to reconstruct task-based stacks across await boundaries.
For example:
python -m profiling.sampling run --async-aware app.py
This is useful when investigating applications built with asyncio or other asynchronous workflows.
You can also control which tasks are included through the --async-mode option:
python -m profiling.sampling run --async-aware --async-mode=all app.py
The available modes are running and all.
The running mode focuses on tasks currently executing on a thread. The all mode also includes tasks suspended while waiting.
This distinction is important when investigating asynchronous applications. A task that is waiting for a network response may not be consuming CPU time, but it can still contribute to overall request latency.
Use wall-clock mode when you want to understand waiting time, and CPU mode when you want to focus on active computation.
Investigating Bytecode With Opcode-Level Profiling
Python executes compiled bytecode instructions. Sometimes a performance issue requires more detail than function-level or source-line profiling can provide.
Tachyon supports opcode-level profiling through the --opcodes option.
python -m profiling.sampling run --opcodes --flamegraph app.py
This option collects information about the bytecode instructions executing at each sample.
Python's adaptive interpreter can specialize certain instructions at runtime. Opcode-aware profiling helps developers inspect these specialized instructions and understand which bytecode operations are active in frequently sampled functions.
Opcode information can be displayed in supported output formats, including flame graphs, heatmaps, and live mode.
However, opcode profiling collects additional information and may require more memory. It can also slightly reduce profiling performance.
Use it when function-level results are not detailed enough to explain a performance issue.
Monitoring an Application With Live Mode
Sometimes developers need to observe an application while it is running instead of generating a report after execution finishes.
Tachyon provides a live terminal interface through the --live option.
python -m profiling.sampling run --live app.py
The live interface displays profiling information as samples are collected. Developers can inspect and sort the available information while the application continues running.
You can also attach to an existing process:
python -m profiling.sampling attach --live 12345
Press q to quit the live interface.
Live mode is useful when investigating performance problems that occur intermittently or when you want to observe application behavior during a specific workload.
Capturing a Single Stack Snapshot
Not every performance investigation requires a complete profiling session.
Sometimes an application becomes unresponsive, and you simply want to understand what its threads are doing at that moment.
Tachyon provides the dump command for this purpose.
python -m profiling.sampling dump 12345
It captures a single stack snapshot and exits.
Unlike attach, dump does not run a continuous sampling loop.
This can be useful when investigating:
An unresponsive Python process.
A thread that appears to be stuck.
A long-running operation.
A process that is waiting unexpectedly.
To inspect all threads, use:
python -m profiling.sampling dump -a 12345
For asynchronous applications, you can also use async-aware stack reconstruction:
python -m profiling.sampling dump --async-aware 12345
The dump command provides a snapshot, not a performance distribution. Use attach or run when you need to understand how execution time is distributed over a period.
Saving and Replaying Profiling Data
Tachyon supports different output formats for analyzing profiling results.
Some important formats include:
Format | Purpose |
|---|
pstats | Function-level statistics compatible with Python's pstats tools |
Flame graph | Interactive visualization of call stacks |
Collapsed stacks | Stack data suitable for external flame graph tools |
Gecko | Timeline-based analysis using Firefox Profiler |
Heatmap | Source-line-level sample visualization |
For example, you can generate a flame graph directly:
python -m profiling.sampling run --flamegraph -o profile.html app.py
You can also save profiling data in binary format and convert it later using the replay command.
python -m profiling.sampling replay profile.bin
To convert a saved profile into an HTML flame graph:
python -m profiling.sampling replay --flamegraph -o output.html profile.bin
This separation between data collection and analysis is useful for teams that want to collect profiling information during a controlled test and inspect it later.
It also makes it possible to generate different visualizations from the same captured profile without running the application again.
Best Practices for Using Tachyon
Tachyon can provide valuable information, but the quality of the results depends on how profiling sessions are configured and interpreted.
Start With the Default Sampling Rate
The default sampling rate is 1 kHz, or 1,000 samples per second.
Start with the default setting before increasing the sampling rate. Higher rates collect more samples but also increase the profiler's own CPU usage.
For most initial investigations, the default configuration is a reasonable starting point.
Profile Under Representative Workloads
A profile collected while an application is idle may not reveal the performance problems experienced by real users.
Run profiling sessions under realistic workloads. For a web application, this might mean generating representative API traffic or executing the same operations that normally cause slow responses.
Compare Wall-Clock and CPU Results
Use both wall-clock and CPU modes when the source of a delay is unclear.
If a function appears prominently in both profiles, it may be performing expensive computation.
If it appears prominently in wall-clock mode but not CPU mode, it may be spending much of its time waiting for an external resource.
This distinction helps developers choose the right optimization strategy.
Avoid Excessively Short Profiling Sessions
Very short profiling sessions may not collect enough samples to produce reliable results.
For an application that runs for only a fraction of a second, sampling may not be the best approach.
Use deterministic tracing or a dedicated microbenchmark when you need more precise information about short operations.
Monitor Sampling Efficiency
Tachyon provides sampling-efficiency information to help evaluate the quality of collected data.
A low sampling efficiency may indicate that the profiler is unable to collect samples at the requested rate. System load, an aggressive sampling interval, or inconsistent process state can affect the results.
Review the number of captured samples and missed samples before drawing conclusions.
Use Blocking Mode Only When Necessary
By default, Tachyon reads the target process's memory without stopping it.
In some cases, rapidly changing stacks can produce incomplete or inconsistent snapshots. The --blocking option pauses the target while its stack is read.
python -m profiling.sampling attach --blocking 12345
Blocking mode can improve stack consistency, but it also pauses the target during each sample.
Avoid combining blocking mode with very high sampling rates. Start with the default non-blocking behavior and enable blocking only when the collected stacks indicate a consistency problem.
Be Careful With Production Permissions
Attaching to a process requires permission to read its memory.
On Linux, this may involve ptrace permissions or CAP_SYS_PTRACE. On Windows, administrative privileges or SeDebugPrivilege may be required. On macOS, task_for_pid permissions and debugger entitlements may apply.
Do not weaken operating-system security settings simply to make profiling easier. Use an approved debugging environment and grant only the permissions needed for the investigation.
Common Mistakes When Using Tachyon
Using the Wrong Python Version
The profiler and target process must use the same Python minor version.
If the target runs Python 3.15, use a compatible Python 3.15 profiler. A profiler running under Python 3.14 cannot attach to that process.
Treating Sample Counts as Exact Execution Times
Tachyon estimates time from collected samples. These estimates are useful for identifying major hotspots, but they are not exact measurements of every function's execution time.
Avoid treating small differences between two profiles as definitive performance improvements.
Using CPU Mode for Network Delays
CPU mode excludes time spent waiting for network responses, file operations, and other blocking activities.
If an API endpoint is slow because of an external service, CPU mode may not reveal the main cause.
Use wall-clock mode to investigate end-to-end delays.
Profiling Only the Main Thread
A multi-threaded application may perform most of its work outside the main thread.
If the profile does not explain the application's behavior, repeat the session with --all-threads.
Increasing the Sampling Rate Too Early
A higher sampling rate does not guarantee more useful results. It can increase the profiler's resource consumption and may reduce sampling efficiency.
Begin with the default rate and increase it only when the investigation requires more detailed sampling.
Advantages and Limitations of Tachyon
Advantages | Limitations |
|---|
Can profile existing Python processes | Requires suitable operating-system permissions |
Does not require application code changes | Requires compatible Python minor versions |
Provides low-overhead sampling | May miss very short-lived functions |
Supports multiple profiling modes | Results are statistical estimates |
Generates interactive visualizations | Higher sampling rates use additional resources |
Supports threads and asynchronous tasks | Some stack snapshots may be inconsistent in non-blocking mode |
Can save and replay profiling data | Not intended to replace precise microbenchmarking |
Tachyon is particularly useful when developers need to investigate performance issues in running applications. However, it should be used alongside testing, benchmarking, logging, and other diagnostic tools rather than as a replacement for them.
Conclusion
Python 3.15's Tachyon profiler provides a built-in way to investigate application performance through statistical sampling. Developers can profile scripts from startup, attach to running processes, inspect multiple threads, analyze asynchronous tasks, and generate visual reports without modifying application code.
Its profiling modes help distinguish CPU-intensive work from waiting time, while flame graphs and heatmaps make it easier to locate frequently sampled functions and source lines.
For production troubleshooting, Tachyon offers a useful way to observe an existing process without introducing function-level instrumentation. For exact call counts, very short operations, or small performance differences, deterministic tracing and dedicated benchmarking tools remain appropriate choices.
By combining Tachyon with realistic workloads and careful analysis, Python developers can identify performance bottlenecks more effectively and make optimization decisions based on actual application behavior.
Join the conversation! Your thoughts help the community grow.