When a Python script feels slow, students often guess which function is the bottleneck or scatter time.perf_counter() calls everywhere. Starting in Python 3.15, the standard library ships with profiling.sampling (codenamed Tachyon)—a built-in statistical sampling profiler that can run a script or attach to an already running process with very low overhead and output an interactive HTML flame graph.
python -m profiling.sampling → Samples Call Stacks → Interactive Flame Graph (HTML)
Why Sampling Beats Guessing
- No code edits needed: You do not import anything or change your script to profile it.
- Works on live processes: Use
attachordumpwith a Process ID (PID) when a background script is already running or stuck. - Built-in HTML visualization: Pass
--flamegraph -o report.htmlto inspect slow call paths right in your browser.
1. Create a Sample Script with a Slow Function
Save this file as grade_report.py. Notice that find_duplicates_slow compares every item in a nested loop while summarize_scores is fast:
def summarize_scores(scores: list[int]) -> float:
return sum(scores) / len(scores)
def find_duplicates_slow(ids: list[int]) -> list[int]:
duplicates = []
for i in range(len(ids)):
for j in range(i + 1, len(ids)):
if ids[i] == ids[j] and ids[i] not in duplicates:
duplicates.append(ids[i])
return duplicates
def main() -> None:
student_ids = list(range(4000)) + [42, 99, 150]
avg = summarize_scores(student_ids)
dups = find_duplicates_slow(student_ids)
print(f"Average: {avg:.1f}, Duplicates: {dups}")
if __name__ == "__main__":
main()
2. Profile the Script and Generate a Flame Graph
Run grade_report.py under Python 3.15's sampling profiler and save an HTML flame graph:
python -m profiling.sampling run --flamegraph -o report.html grade_report.py
Open report.html in your browser. The widest horizontal bar immediately points to find_duplicates_slow instead of summarize_scores.
3. Useful Subcommands for Running Apps
python -m profiling.sampling run ...launches a script or module (-m module_name) under the profiler.python -m profiling.sampling attach --mode cpu -d 10 --flamegraph -o live.html 12345attaches to an active Python PID (12345) for 10 seconds without restarting it.python -m profiling.sampling dump 12345prints an instant stack traceback if a running program appears frozen.
Practice
- Replace the nested loop in
find_duplicates_slowwith asetcheck, rerunprofiling.sampling run, and compare the flame graph width. - Profile a Python module using the
-mflag instead of a file path. - Try generating a
--geckoprofile output and note how timeline formats differ from flame graphs.
Continue learning: Python Tutorial for Beginners: Complete Learning Path.
References: Python 3.15 Documentation.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.