2025-09-09 23:06:45 +01:00
|
|
|
import base64
|
2025-07-10 18:44:24 +01:00
|
|
|
import collections
|
2025-09-09 23:06:45 +01:00
|
|
|
import functools
|
|
|
|
|
import importlib.resources
|
|
|
|
|
import json
|
|
|
|
|
import linecache
|
2025-07-10 18:44:24 +01:00
|
|
|
import os
|
2025-12-12 15:06:28 +00:00
|
|
|
import sys
|
2026-01-02 02:31:39 +00:00
|
|
|
import sysconfig
|
2025-07-10 18:44:24 +01:00
|
|
|
|
2025-12-02 20:33:40 +00:00
|
|
|
from ._css_utils import get_combined_css
|
2025-12-11 03:41:47 +00:00
|
|
|
from .collector import Collector, extract_lineno
|
|
|
|
|
from .opcode_utils import get_opcode_mapping
|
2025-09-14 23:47:14 +01:00
|
|
|
from .string_table import StringTable
|
2025-07-10 18:44:24 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class StackTraceCollector(Collector):
|
2025-11-24 11:45:08 +00:00
|
|
|
def __init__(self, sample_interval_usec, *, skip_idle=False):
|
|
|
|
|
self.sample_interval_usec = sample_interval_usec
|
2025-09-19 19:17:28 +01:00
|
|
|
self.skip_idle = skip_idle
|
|
|
|
|
|
2025-12-22 23:57:20 +00:00
|
|
|
def collect(self, stack_frames, timestamps_us=None, skip_idle=False):
|
|
|
|
|
weight = len(timestamps_us) if timestamps_us else 1
|
|
|
|
|
for frames, thread_id in self._iter_stacks(stack_frames, skip_idle=skip_idle):
|
|
|
|
|
self.process_frames(frames, thread_id, weight=weight)
|
2025-09-14 23:47:14 +01:00
|
|
|
|
2025-12-22 23:57:20 +00:00
|
|
|
def process_frames(self, frames, thread_id, weight=1):
|
2025-09-14 23:47:14 +01:00
|
|
|
pass
|
2025-07-10 18:44:24 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class CollapsedStackCollector(StackTraceCollector):
|
2025-09-19 19:17:28 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super().__init__(*args, **kwargs)
|
2025-09-14 23:47:14 +01:00
|
|
|
self.stack_counter = collections.Counter()
|
|
|
|
|
|
2025-12-22 23:57:20 +00:00
|
|
|
def process_frames(self, frames, thread_id, weight=1):
|
2025-12-11 03:41:47 +00:00
|
|
|
# Extract only (filename, lineno, funcname) - opcode not needed for collapsed stacks
|
|
|
|
|
# frame is (filename, location, funcname, opcode)
|
|
|
|
|
call_tree = tuple(
|
|
|
|
|
(f[0], extract_lineno(f[1]), f[2]) for f in reversed(frames)
|
|
|
|
|
)
|
2025-12-22 23:57:20 +00:00
|
|
|
self.stack_counter[(call_tree, thread_id)] += weight
|
2025-09-14 23:47:14 +01:00
|
|
|
|
2025-07-10 18:44:24 +01:00
|
|
|
def export(self, filename):
|
2025-09-14 23:47:14 +01:00
|
|
|
lines = []
|
2025-09-25 15:34:57 +01:00
|
|
|
for (call_tree, thread_id), count in self.stack_counter.items():
|
2025-11-17 05:39:00 -08:00
|
|
|
parts = [f"tid:{thread_id}"]
|
|
|
|
|
for file, line, func in call_tree:
|
|
|
|
|
# This is what pstats does for "special" frames:
|
|
|
|
|
if file == "~" and line == 0:
|
|
|
|
|
part = func
|
|
|
|
|
else:
|
|
|
|
|
part = f"{os.path.basename(file)}:{func}:{line}"
|
|
|
|
|
parts.append(part)
|
|
|
|
|
stack_str = ";".join(parts)
|
|
|
|
|
lines.append((stack_str, count))
|
2025-09-14 23:47:14 +01:00
|
|
|
|
|
|
|
|
lines.sort(key=lambda x: (-x[1], x[0]))
|
2025-07-10 18:44:24 +01:00
|
|
|
|
|
|
|
|
with open(filename, "w") as f:
|
2025-09-14 23:47:14 +01:00
|
|
|
for stack, count in lines:
|
2025-07-10 18:44:24 +01:00
|
|
|
f.write(f"{stack} {count}\n")
|
|
|
|
|
print(f"Collapsed stack output written to {filename}")
|
2025-09-09 23:06:45 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class FlamegraphCollector(StackTraceCollector):
|
2025-09-19 19:17:28 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super().__init__(*args, **kwargs)
|
2025-09-09 23:06:45 +01:00
|
|
|
self.stats = {}
|
2025-09-25 15:34:57 +01:00
|
|
|
self._root = {"samples": 0, "children": {}, "threads": set()}
|
2025-09-14 23:47:14 +01:00
|
|
|
self._total_samples = 0
|
2025-11-30 01:42:39 +00:00
|
|
|
self._sample_count = 0 # Track actual number of samples (not thread traces)
|
2025-09-14 23:47:14 +01:00
|
|
|
self._func_intern = {}
|
|
|
|
|
self._string_table = StringTable()
|
2025-09-25 15:34:57 +01:00
|
|
|
self._all_threads = set()
|
2025-09-09 23:06:45 +01:00
|
|
|
|
2025-11-30 01:42:39 +00:00
|
|
|
# Thread status statistics (similar to LiveStatsCollector)
|
|
|
|
|
self.thread_status_counts = {
|
|
|
|
|
"has_gil": 0,
|
|
|
|
|
"on_cpu": 0,
|
|
|
|
|
"gil_requested": 0,
|
|
|
|
|
"unknown": 0,
|
2025-12-11 20:46:34 +00:00
|
|
|
"has_exception": 0,
|
2025-11-30 01:42:39 +00:00
|
|
|
"total": 0,
|
|
|
|
|
}
|
|
|
|
|
self.samples_with_gc_frames = 0
|
|
|
|
|
|
|
|
|
|
# Per-thread statistics
|
2025-12-11 20:46:34 +00:00
|
|
|
self.per_thread_stats = {} # {thread_id: {has_gil, on_cpu, gil_requested, unknown, has_exception, total, gc_samples}}
|
2025-11-30 01:42:39 +00:00
|
|
|
|
2025-12-22 23:57:20 +00:00
|
|
|
def collect(self, stack_frames, timestamps_us=None, skip_idle=False):
|
2025-11-30 01:42:39 +00:00
|
|
|
"""Override to track thread status statistics before processing frames."""
|
2025-12-22 23:57:20 +00:00
|
|
|
# Weight is number of timestamps (samples with identical stack)
|
|
|
|
|
weight = len(timestamps_us) if timestamps_us else 1
|
|
|
|
|
|
|
|
|
|
# Increment sample count by weight
|
|
|
|
|
self._sample_count += weight
|
2025-11-30 01:42:39 +00:00
|
|
|
|
|
|
|
|
# Collect both aggregate and per-thread statistics using base method
|
|
|
|
|
status_counts, has_gc_frame, per_thread_stats = self._collect_thread_status_stats(stack_frames)
|
|
|
|
|
|
2025-12-22 23:57:20 +00:00
|
|
|
# Merge aggregate status counts (multiply by weight)
|
2025-11-30 01:42:39 +00:00
|
|
|
for key in status_counts:
|
2025-12-22 23:57:20 +00:00
|
|
|
self.thread_status_counts[key] += status_counts[key] * weight
|
2025-11-30 01:42:39 +00:00
|
|
|
|
|
|
|
|
# Update aggregate GC frame count
|
|
|
|
|
if has_gc_frame:
|
2025-12-22 23:57:20 +00:00
|
|
|
self.samples_with_gc_frames += weight
|
2025-11-30 01:42:39 +00:00
|
|
|
|
2025-12-22 23:57:20 +00:00
|
|
|
# Merge per-thread statistics (multiply by weight)
|
2025-11-30 01:42:39 +00:00
|
|
|
for thread_id, stats in per_thread_stats.items():
|
|
|
|
|
if thread_id not in self.per_thread_stats:
|
|
|
|
|
self.per_thread_stats[thread_id] = {
|
|
|
|
|
"has_gil": 0,
|
|
|
|
|
"on_cpu": 0,
|
|
|
|
|
"gil_requested": 0,
|
|
|
|
|
"unknown": 0,
|
2025-12-11 20:46:34 +00:00
|
|
|
"has_exception": 0,
|
2025-11-30 01:42:39 +00:00
|
|
|
"total": 0,
|
|
|
|
|
"gc_samples": 0,
|
|
|
|
|
}
|
|
|
|
|
for key, value in stats.items():
|
2025-12-22 23:57:20 +00:00
|
|
|
self.per_thread_stats[thread_id][key] += value * weight
|
2025-11-30 01:42:39 +00:00
|
|
|
|
|
|
|
|
# Call parent collect to process frames
|
2025-12-22 23:57:20 +00:00
|
|
|
super().collect(stack_frames, timestamps_us, skip_idle=skip_idle)
|
2025-11-30 01:42:39 +00:00
|
|
|
|
2025-12-01 17:34:14 +00:00
|
|
|
def set_stats(self, sample_interval_usec, duration_sec, sample_rate,
|
|
|
|
|
error_rate=None, missed_samples=None, mode=None):
|
2025-09-09 23:06:45 +01:00
|
|
|
"""Set profiling statistics to include in flamegraph data."""
|
|
|
|
|
self.stats = {
|
|
|
|
|
"sample_interval_usec": sample_interval_usec,
|
|
|
|
|
"duration_sec": duration_sec,
|
|
|
|
|
"sample_rate": sample_rate,
|
2025-11-30 01:42:39 +00:00
|
|
|
"error_rate": error_rate,
|
2025-12-01 17:34:14 +00:00
|
|
|
"missed_samples": missed_samples,
|
2025-11-30 01:42:39 +00:00
|
|
|
"mode": mode
|
2025-09-09 23:06:45 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
def export(self, filename):
|
|
|
|
|
flamegraph_data = self._convert_to_flamegraph_format()
|
|
|
|
|
|
2025-09-14 23:47:14 +01:00
|
|
|
# Debug output with string table statistics
|
2025-09-09 23:06:45 +01:00
|
|
|
num_functions = len(flamegraph_data.get("children", []))
|
|
|
|
|
total_time = flamegraph_data.get("value", 0)
|
2025-09-14 23:47:14 +01:00
|
|
|
string_count = len(self._string_table)
|
2025-09-09 23:06:45 +01:00
|
|
|
print(
|
2025-09-14 23:47:14 +01:00
|
|
|
f"Flamegraph data: {num_functions} root functions, total samples: {total_time}, "
|
|
|
|
|
f"{string_count} unique strings"
|
2025-09-09 23:06:45 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if num_functions == 0:
|
|
|
|
|
print(
|
|
|
|
|
"Warning: No functions found in profiling data. Check if sampling captured any data."
|
|
|
|
|
)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
html_content = self._create_flamegraph_html(flamegraph_data)
|
|
|
|
|
|
|
|
|
|
with open(filename, "w", encoding="utf-8") as f:
|
|
|
|
|
f.write(html_content)
|
|
|
|
|
|
|
|
|
|
print(f"Flamegraph saved to: {filename}")
|
|
|
|
|
|
2025-09-10 01:08:09 +01:00
|
|
|
@staticmethod
|
2025-09-09 23:06:45 +01:00
|
|
|
@functools.lru_cache(maxsize=None)
|
2025-09-10 01:08:09 +01:00
|
|
|
def _format_function_name(func):
|
2025-09-09 23:06:45 +01:00
|
|
|
filename, lineno, funcname = func
|
|
|
|
|
|
2025-11-17 05:39:00 -08:00
|
|
|
# Special frames like <GC> and <native> should not show file:line
|
|
|
|
|
if filename == "~" and lineno == 0:
|
|
|
|
|
return funcname
|
|
|
|
|
|
2025-09-09 23:06:45 +01:00
|
|
|
if len(filename) > 50:
|
|
|
|
|
parts = filename.split("/")
|
|
|
|
|
if len(parts) > 2:
|
|
|
|
|
filename = f".../{'/'.join(parts[-2:])}"
|
|
|
|
|
|
|
|
|
|
return f"{funcname} ({filename}:{lineno})"
|
|
|
|
|
|
|
|
|
|
def _convert_to_flamegraph_format(self):
|
2025-09-14 23:47:14 +01:00
|
|
|
if self._total_samples == 0:
|
|
|
|
|
return {
|
|
|
|
|
"name": self._string_table.intern("No Data"),
|
|
|
|
|
"value": 0,
|
2025-09-09 23:06:45 +01:00
|
|
|
"children": [],
|
2025-09-25 15:34:57 +01:00
|
|
|
"threads": [],
|
2025-09-14 23:47:14 +01:00
|
|
|
"strings": self._string_table.get_strings()
|
2025-09-09 23:06:45 +01:00
|
|
|
}
|
|
|
|
|
|
2025-09-14 23:47:14 +01:00
|
|
|
def convert_children(children, min_samples):
|
|
|
|
|
out = []
|
|
|
|
|
for func, node in children.items():
|
|
|
|
|
samples = node["samples"]
|
|
|
|
|
if samples < min_samples:
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# Intern all string components for maximum efficiency
|
|
|
|
|
filename_idx = self._string_table.intern(func[0])
|
|
|
|
|
funcname_idx = self._string_table.intern(func[2])
|
|
|
|
|
name_idx = self._string_table.intern(self._format_function_name(func))
|
|
|
|
|
|
|
|
|
|
child_entry = {
|
|
|
|
|
"name": name_idx,
|
|
|
|
|
"value": samples,
|
|
|
|
|
"children": [],
|
|
|
|
|
"filename": filename_idx,
|
|
|
|
|
"lineno": func[1],
|
|
|
|
|
"funcname": funcname_idx,
|
2025-09-25 15:34:57 +01:00
|
|
|
"threads": sorted(list(node.get("threads", set()))),
|
2025-09-14 23:47:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
source = self._get_source_lines(func)
|
|
|
|
|
if source:
|
|
|
|
|
# Intern source lines for memory efficiency
|
|
|
|
|
source_indices = [self._string_table.intern(line) for line in source]
|
|
|
|
|
child_entry["source"] = source_indices
|
|
|
|
|
|
2025-12-11 03:41:47 +00:00
|
|
|
# Include opcode data if available
|
|
|
|
|
opcodes = node.get("opcodes", {})
|
|
|
|
|
if opcodes:
|
|
|
|
|
child_entry["opcodes"] = dict(opcodes)
|
|
|
|
|
|
2025-09-14 23:47:14 +01:00
|
|
|
# Recurse
|
|
|
|
|
child_entry["children"] = convert_children(
|
|
|
|
|
node["children"], min_samples
|
2025-09-09 23:06:45 +01:00
|
|
|
)
|
2025-09-14 23:47:14 +01:00
|
|
|
out.append(child_entry)
|
2025-09-09 23:06:45 +01:00
|
|
|
|
2025-09-14 23:47:14 +01:00
|
|
|
# Sort by value (descending) then by name index for consistent ordering
|
|
|
|
|
out.sort(key=lambda x: (-x["value"], x["name"]))
|
|
|
|
|
return out
|
2025-09-09 23:06:45 +01:00
|
|
|
|
|
|
|
|
# Filter out very small functions (less than 0.1% of total samples)
|
2025-09-14 23:47:14 +01:00
|
|
|
total_samples = self._total_samples
|
2025-09-09 23:06:45 +01:00
|
|
|
min_samples = max(1, int(total_samples * 0.001))
|
|
|
|
|
|
2025-09-14 23:47:14 +01:00
|
|
|
root_children = convert_children(self._root["children"], min_samples)
|
|
|
|
|
if not root_children:
|
|
|
|
|
return {
|
|
|
|
|
"name": self._string_table.intern("No significant data"),
|
|
|
|
|
"value": 0,
|
|
|
|
|
"children": [],
|
|
|
|
|
"strings": self._string_table.get_strings()
|
|
|
|
|
}
|
2025-09-09 23:06:45 +01:00
|
|
|
|
2025-11-30 01:42:39 +00:00
|
|
|
# Calculate thread status percentages for display
|
2025-12-11 20:46:34 +00:00
|
|
|
is_free_threaded = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
|
2025-11-30 01:42:39 +00:00
|
|
|
total_threads = max(1, self.thread_status_counts["total"])
|
|
|
|
|
thread_stats = {
|
|
|
|
|
"has_gil_pct": (self.thread_status_counts["has_gil"] / total_threads) * 100,
|
|
|
|
|
"on_cpu_pct": (self.thread_status_counts["on_cpu"] / total_threads) * 100,
|
|
|
|
|
"gil_requested_pct": (self.thread_status_counts["gil_requested"] / total_threads) * 100,
|
2025-12-11 20:46:34 +00:00
|
|
|
"has_exception_pct": (self.thread_status_counts["has_exception"] / total_threads) * 100,
|
2025-11-30 01:42:39 +00:00
|
|
|
"gc_pct": (self.samples_with_gc_frames / max(1, self._sample_count)) * 100,
|
2025-12-11 20:46:34 +00:00
|
|
|
"free_threaded": is_free_threaded,
|
2025-11-30 01:42:39 +00:00
|
|
|
**self.thread_status_counts
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Calculate per-thread statistics with percentages
|
|
|
|
|
per_thread_stats_with_pct = {}
|
|
|
|
|
total_samples_denominator = max(1, self._sample_count)
|
|
|
|
|
for thread_id, stats in self.per_thread_stats.items():
|
|
|
|
|
total = max(1, stats["total"])
|
|
|
|
|
per_thread_stats_with_pct[thread_id] = {
|
|
|
|
|
"has_gil_pct": (stats["has_gil"] / total) * 100,
|
|
|
|
|
"on_cpu_pct": (stats["on_cpu"] / total) * 100,
|
|
|
|
|
"gil_requested_pct": (stats["gil_requested"] / total) * 100,
|
2025-12-11 20:46:34 +00:00
|
|
|
"has_exception_pct": (stats["has_exception"] / total) * 100,
|
2025-11-30 01:42:39 +00:00
|
|
|
"gc_pct": (stats["gc_samples"] / total_samples_denominator) * 100,
|
|
|
|
|
**stats
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-11 03:41:47 +00:00
|
|
|
# Build opcode mapping for JS
|
|
|
|
|
opcode_mapping = get_opcode_mapping()
|
|
|
|
|
|
2025-09-09 23:06:45 +01:00
|
|
|
# If we only have one root child, make it the root to avoid redundant level
|
2025-09-14 23:47:14 +01:00
|
|
|
if len(root_children) == 1:
|
|
|
|
|
main_child = root_children[0]
|
|
|
|
|
# Update the name to indicate it's the program root
|
|
|
|
|
old_name = self._string_table.get_string(main_child["name"])
|
|
|
|
|
new_name = f"Program Root: {old_name}"
|
|
|
|
|
main_child["name"] = self._string_table.intern(new_name)
|
2025-11-30 01:42:39 +00:00
|
|
|
main_child["stats"] = {
|
|
|
|
|
**self.stats,
|
|
|
|
|
"thread_stats": thread_stats,
|
|
|
|
|
"per_thread_stats": per_thread_stats_with_pct
|
|
|
|
|
}
|
2025-09-25 15:34:57 +01:00
|
|
|
main_child["threads"] = sorted(list(self._all_threads))
|
2025-09-14 23:47:14 +01:00
|
|
|
main_child["strings"] = self._string_table.get_strings()
|
2025-12-11 03:41:47 +00:00
|
|
|
main_child["opcode_mapping"] = opcode_mapping
|
2025-09-09 23:06:45 +01:00
|
|
|
return main_child
|
|
|
|
|
|
2025-09-14 23:47:14 +01:00
|
|
|
return {
|
|
|
|
|
"name": self._string_table.intern("Program Root"),
|
|
|
|
|
"value": total_samples,
|
|
|
|
|
"children": root_children,
|
2025-11-30 01:42:39 +00:00
|
|
|
"stats": {
|
|
|
|
|
**self.stats,
|
|
|
|
|
"thread_stats": thread_stats,
|
|
|
|
|
"per_thread_stats": per_thread_stats_with_pct
|
|
|
|
|
},
|
2025-09-25 15:34:57 +01:00
|
|
|
"threads": sorted(list(self._all_threads)),
|
2025-12-11 03:41:47 +00:00
|
|
|
"strings": self._string_table.get_strings(),
|
|
|
|
|
"opcode_mapping": opcode_mapping
|
2025-09-14 23:47:14 +01:00
|
|
|
}
|
|
|
|
|
|
2025-12-22 23:57:20 +00:00
|
|
|
def process_frames(self, frames, thread_id, weight=1):
|
2025-12-11 03:41:47 +00:00
|
|
|
"""Process stack frames into flamegraph tree structure.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
frames: List of (filename, location, funcname, opcode) tuples in
|
|
|
|
|
leaf-to-root order. location is (lineno, end_lineno, col_offset, end_col_offset).
|
|
|
|
|
opcode is None if not gathered.
|
|
|
|
|
thread_id: Thread ID for this stack trace
|
2025-12-22 23:57:20 +00:00
|
|
|
weight: Number of samples this stack represents (for batched RLE)
|
2025-12-11 03:41:47 +00:00
|
|
|
"""
|
|
|
|
|
# Reverse to root->leaf order for tree building
|
2025-12-22 23:57:20 +00:00
|
|
|
self._root["samples"] += weight
|
|
|
|
|
self._total_samples += weight
|
2025-09-25 15:34:57 +01:00
|
|
|
self._root["threads"].add(thread_id)
|
|
|
|
|
self._all_threads.add(thread_id)
|
2025-09-14 23:47:14 +01:00
|
|
|
|
|
|
|
|
current = self._root
|
2025-12-11 03:41:47 +00:00
|
|
|
for filename, location, funcname, opcode in reversed(frames):
|
|
|
|
|
lineno = extract_lineno(location)
|
|
|
|
|
func = (filename, lineno, funcname)
|
2025-09-14 23:47:14 +01:00
|
|
|
func = self._func_intern.setdefault(func, func)
|
2025-12-11 03:41:47 +00:00
|
|
|
|
|
|
|
|
node = current["children"].get(func)
|
2025-09-14 23:47:14 +01:00
|
|
|
if node is None:
|
2025-12-11 03:41:47 +00:00
|
|
|
node = {"samples": 0, "children": {}, "threads": set(), "opcodes": collections.Counter()}
|
|
|
|
|
current["children"][func] = node
|
2025-12-22 23:57:20 +00:00
|
|
|
node["samples"] += weight
|
2025-09-25 15:34:57 +01:00
|
|
|
node["threads"].add(thread_id)
|
2025-12-11 03:41:47 +00:00
|
|
|
|
|
|
|
|
if opcode is not None:
|
2025-12-22 23:57:20 +00:00
|
|
|
node["opcodes"][opcode] += weight
|
2025-12-11 03:41:47 +00:00
|
|
|
|
2025-09-14 23:47:14 +01:00
|
|
|
current = node
|
2025-09-09 23:06:45 +01:00
|
|
|
|
|
|
|
|
def _get_source_lines(self, func):
|
2025-09-14 23:47:14 +01:00
|
|
|
filename, lineno, _ = func
|
2025-09-09 23:06:45 +01:00
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
lines = []
|
|
|
|
|
start_line = max(1, lineno - 2)
|
|
|
|
|
end_line = lineno + 3
|
|
|
|
|
|
|
|
|
|
for line_num in range(start_line, end_line):
|
|
|
|
|
line = linecache.getline(filename, line_num)
|
|
|
|
|
if line.strip():
|
|
|
|
|
marker = "→ " if line_num == lineno else " "
|
|
|
|
|
lines.append(f"{marker}{line_num}: {line.rstrip()}")
|
|
|
|
|
|
|
|
|
|
return lines if lines else None
|
|
|
|
|
|
|
|
|
|
except Exception:
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
def _create_flamegraph_html(self, data):
|
|
|
|
|
data_json = json.dumps(data)
|
|
|
|
|
|
|
|
|
|
template_dir = importlib.resources.files(__package__)
|
|
|
|
|
vendor_dir = template_dir / "_vendor"
|
|
|
|
|
assets_dir = template_dir / "_assets"
|
|
|
|
|
|
|
|
|
|
d3_path = vendor_dir / "d3" / "7.8.5" / "d3.min.js"
|
|
|
|
|
d3_flame_graph_dir = vendor_dir / "d3-flame-graph" / "4.1.3"
|
|
|
|
|
fg_css_path = d3_flame_graph_dir / "d3-flamegraph.css"
|
|
|
|
|
fg_js_path = d3_flame_graph_dir / "d3-flamegraph.min.js"
|
|
|
|
|
fg_tooltip_js_path = d3_flame_graph_dir / "d3-flamegraph-tooltip.min.js"
|
|
|
|
|
|
2025-12-02 20:33:40 +00:00
|
|
|
html_template = (template_dir / "_flamegraph_assets" / "flamegraph_template.html").read_text(encoding="utf-8")
|
|
|
|
|
css_content = get_combined_css("flamegraph")
|
|
|
|
|
js_content = (template_dir / "_flamegraph_assets" / "flamegraph.js").read_text(encoding="utf-8")
|
2025-09-09 23:06:45 +01:00
|
|
|
|
|
|
|
|
# Inline first-party CSS/JS
|
|
|
|
|
html_template = html_template.replace(
|
|
|
|
|
"<!-- INLINE_CSS -->", f"<style>\n{css_content}\n</style>"
|
|
|
|
|
)
|
|
|
|
|
html_template = html_template.replace(
|
|
|
|
|
"<!-- INLINE_JS -->", f"<script>\n{js_content}\n</script>"
|
|
|
|
|
)
|
|
|
|
|
|
gh-140727: Restructure profiling documentation for PEP 799 (#142373)
* Add profiling module documentation structure
PEP 799 introduces a new `profiling` package that reorganizes Python's
profiling tools under a unified namespace. This commit adds the documentation
structure to match: a main entry point (profiling.rst) that helps users choose
between profilers, detailed docs for the tracing profiler (profiling-tracing.rst),
and separated pstats documentation.
The tracing profiler docs note that cProfile remains as a backward-compatible
alias, so existing code continues to work. The pstats module gets its own page
since it's used by both profiler types and deserves focused documentation.
* Add profiling.sampling documentation
The sampling profiler is new in Python 3.15 and works fundamentally differently
from the tracing profiler. It observes programs from outside by periodically
capturing stack snapshots, which means zero overhead on the profiled code. This
makes it practical for production use where you can attach to live servers.
The docs explain the key concepts (statistical vs deterministic profiling),
provide quick examples upfront, document all output formats (pstats, flamegraph,
gecko, heatmap), and cover the live TUI mode. The defaults table helps users
understand what happens without any flags.
* Wire profiling docs into the documentation tree
Add the new profiling module pages to the Debugging and Profiling toctree.
The order places the main profiling.rst entry point first, followed by the
two profiler implementations, then pstats, and finally the deprecated profile
module last.
* Convert profile.rst to deprecation stub
The pure Python profile module is deprecated in 3.15 and scheduled for removal
in 3.17. Users should migrate to profiling.tracing (or use the cProfile alias
which continues to work).
The page now focuses on helping existing users migrate: it shows the old vs new
import style, keeps the shared API reference since both modules have the same
interface, and preserves the calibration docs for anyone still using the pure
Python implementation during the transition period.
* Update CLI module references for profiling restructure
Point cProfile to profiling.tracing docs and add profiling.sampling to the
list of modules with CLI interfaces. The old profile-cli label no longer
exists after the documentation restructure.
* Update whatsnew to link to profiling module docs
Enable cross-references to the new profiling module documentation and update
the CLI examples to use the current syntax with the attach subcommand. Also
reference profiling.tracing instead of cProfile since that's the new canonical
name.
2025-12-09 12:55:04 +00:00
|
|
|
png_path = assets_dir / "tachyon-logo.png"
|
2025-09-09 23:06:45 +01:00
|
|
|
b64_logo = base64.b64encode(png_path.read_bytes()).decode("ascii")
|
|
|
|
|
|
|
|
|
|
# Let CSS control size; keep markup simple
|
gh-140727: Restructure profiling documentation for PEP 799 (#142373)
* Add profiling module documentation structure
PEP 799 introduces a new `profiling` package that reorganizes Python's
profiling tools under a unified namespace. This commit adds the documentation
structure to match: a main entry point (profiling.rst) that helps users choose
between profilers, detailed docs for the tracing profiler (profiling-tracing.rst),
and separated pstats documentation.
The tracing profiler docs note that cProfile remains as a backward-compatible
alias, so existing code continues to work. The pstats module gets its own page
since it's used by both profiler types and deserves focused documentation.
* Add profiling.sampling documentation
The sampling profiler is new in Python 3.15 and works fundamentally differently
from the tracing profiler. It observes programs from outside by periodically
capturing stack snapshots, which means zero overhead on the profiled code. This
makes it practical for production use where you can attach to live servers.
The docs explain the key concepts (statistical vs deterministic profiling),
provide quick examples upfront, document all output formats (pstats, flamegraph,
gecko, heatmap), and cover the live TUI mode. The defaults table helps users
understand what happens without any flags.
* Wire profiling docs into the documentation tree
Add the new profiling module pages to the Debugging and Profiling toctree.
The order places the main profiling.rst entry point first, followed by the
two profiler implementations, then pstats, and finally the deprecated profile
module last.
* Convert profile.rst to deprecation stub
The pure Python profile module is deprecated in 3.15 and scheduled for removal
in 3.17. Users should migrate to profiling.tracing (or use the cProfile alias
which continues to work).
The page now focuses on helping existing users migrate: it shows the old vs new
import style, keeps the shared API reference since both modules have the same
interface, and preserves the calibration docs for anyone still using the pure
Python implementation during the transition period.
* Update CLI module references for profiling restructure
Point cProfile to profiling.tracing docs and add profiling.sampling to the
list of modules with CLI interfaces. The old profile-cli label no longer
exists after the documentation restructure.
* Update whatsnew to link to profiling module docs
Enable cross-references to the new profiling module documentation and update
the CLI examples to use the current syntax with the attach subcommand. Also
reference profiling.tracing instead of cProfile since that's the new canonical
name.
2025-12-09 12:55:04 +00:00
|
|
|
logo_html = f'<img src="data:image/png;base64,{b64_logo}" alt="Tachyon logo"/>'
|
2025-09-09 23:06:45 +01:00
|
|
|
html_template = html_template.replace("<!-- INLINE_LOGO -->", logo_html)
|
2025-12-12 15:06:28 +00:00
|
|
|
html_template = html_template.replace(
|
|
|
|
|
"<!-- PYTHON_VERSION -->", f"{sys.version_info.major}.{sys.version_info.minor}"
|
|
|
|
|
)
|
2025-09-09 23:06:45 +01:00
|
|
|
|
|
|
|
|
d3_js = d3_path.read_text(encoding="utf-8")
|
|
|
|
|
fg_css = fg_css_path.read_text(encoding="utf-8")
|
|
|
|
|
fg_js = fg_js_path.read_text(encoding="utf-8")
|
|
|
|
|
fg_tooltip_js = fg_tooltip_js_path.read_text(encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
html_template = html_template.replace(
|
|
|
|
|
"<!-- INLINE_VENDOR_D3_JS -->",
|
|
|
|
|
f"<script>\n{d3_js}\n</script>",
|
|
|
|
|
)
|
|
|
|
|
html_template = html_template.replace(
|
|
|
|
|
"<!-- INLINE_VENDOR_FLAMEGRAPH_CSS -->",
|
|
|
|
|
f"<style>\n{fg_css}\n</style>",
|
|
|
|
|
)
|
|
|
|
|
html_template = html_template.replace(
|
|
|
|
|
"<!-- INLINE_VENDOR_FLAMEGRAPH_JS -->",
|
|
|
|
|
f"<script>\n{fg_js}\n</script>",
|
|
|
|
|
)
|
|
|
|
|
html_template = html_template.replace(
|
|
|
|
|
"<!-- INLINE_VENDOR_FLAMEGRAPH_TOOLTIP_JS -->",
|
|
|
|
|
f"<script>\n{fg_tooltip_js}\n</script>",
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Replace the placeholder with actual data
|
|
|
|
|
html_content = html_template.replace(
|
|
|
|
|
"{{FLAMEGRAPH_DATA}}", data_json
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return html_content
|