The user wants a comprehensive performance profiling program. Let me think about what features to include:
- Flamegraphs - Visual representation of call stacks showing where time is spent
- Allocation tracing - Track memory allocations and identify hot spots
- P95/P99 latency metrics - Focus on tail latencies, not just averages
- Regression guards - Automated checks to catch performance regressions
I'll create a sophisticated profiling toolkit that includes:
- A profiler that samples stack traces and generates flamegraph data
- Memory allocation tracking
- Latency histogram with percentile calculations
- Baseline comparison for regression detection
- A real-time monitoring dashboard (TUI)
Let me structure this as a comprehensive performance analysis library with:
profiler.py - Core profiling functionality
flamegraph.py - Flamegraph generation
allocations.py - Memory allocation tracking
metrics.py - P95/P99 and other metrics
regression.py - Regression detection
main.py - Demo program
Actually, let me create a single comprehensive file that demonstrates all these concepts, since the user asked for "a program". I'll make it modular but contained.
Key features to implement:
- Stack sampling profiler
- Flamegraph SVG generation
- Memory allocation tracking with tracemalloc
- Latency histogram with percentiles
- Baseline storage and comparison
- CLI interface for running profiles
- Decorator for easy function profiling
- Context managers for code block profiling
- Real-time stats display
Let me write this comprehensively.
Performance Profiling Toolkit
A comprehensive performance profiling solution with flamegraphs, allocation tracing, P95/P99 metrics, and regression guards.
Installation
pip install richclick
Complete Implementation
#!/usr/bin/env python3
"""
Performance Profiling Toolkit
Features:
- Flamegraph generation from stack samples
- Memory allocation tracing
- P95/P99 latency metrics with histograms
- Regression guards with baseline comparison
"""
from __future__ import annotations
import asyncio
import cProfile
import functools
import io
import json
import logging
import math
import os
import pstats
import random
import statistics
import sys
import threading
import time
import traceback
import tracemalloc
from collections import defaultdict
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union
# Rich for beautiful terminal output
try:
from rich.console import Console
from rich.panel import Panel
from rich.progress import BarColumn, Progress, TextColumn, TimeColumn
from rich.table import Table
from rich.text import Text
RICH_AVAILABLE = True
except ImportError:
RICH_AVAILABLE = False
# Type aliases
T = TypeVar('T')
Millis = float
Bytes = int
# ============================================================================
# DATA STRUCTURES
# ============================================================================
@dataclass
class ProfileSample:
"""A single profile sample containing stack trace and timing."""
timestamp: float
stack: List[str]
thread_name: str
cpu_time: float = 0.0
@dataclass
class AllocationRecord:
"""Memory allocation record."""
size: Bytes
count: int
traceback: List[str]
peak_time: Optional[float] = None
@dataclass
class LatencyMetric:
"""Single latency measurement."""
operation: str
duration_ms: Millis
timestamp: float
success: bool = True
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class PercentileStats:
"""Percentile statistics for latency."""
p50: Millis
p90: Millis
p95: Millis
p99: Millis
p999: Millis
min: Millis
max: Millis
mean: Millis
std: Millis
count: int
@dataclass
class RegressionResult:
"""Result of regression check."""
metric_name: str
baseline_value: float
current_value: float
change_percent: float
threshold_percent: float
is_regression: bool
severity: str # "none", "warning", "critical"
# ============================================================================
# LATENCY HISTOGRAM - P95/P99 TRACKING
# ============================================================================
class LatencyHistogram:
"""
High-performance latency histogram with P95/P99 calculations.
Uses bucketed storage for memory efficiency.
"""
# Latency buckets in milliseconds (logarithmic scale)
BUCKET_BOUNDS = [
0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000
]
def __init__(self, name: str, max_samples: int = 100000):
self.name = name
self.max_samples = max_samples
self._samples: List[float] = []
self._bucket_counts: Dict[int, int] = defaultdict(int)
self._lock = threading.Lock()
self._total = 0.0
self._count = 0
self._min = float('inf')
self._max = 0.0
def record(self, latency_ms: Millis) -> None:
"""Record a latency measurement."""
with self._lock:
self._samples.append(latency_ms)
self._total += latency_ms
self._count += 1
self._min = min(self._min, latency_ms)
self._max = max(self._max, latency_ms)
# Update bucket
bucket = self._find_bucket(latency_ms)
self._bucket_counts[bucket] += 1
# Trim old samples if needed
if len(self._samples) > self.max_samples:
removed = self._samples.pop(0)
bucket = self._find_bucket(removed)
self._bucket_counts[bucket] -= 1
def _find_bucket(self, value: float) -> int:
"""Find the bucket index for a value."""
for i, bound in enumerate(self.BUCKET_BOUNDS):
if value < bound:
return i
return len(self.BUCKET_BOUNDS)
def _bucket_label(self, idx: int) -> str:
"""Get label for a bucket."""
if idx == 0:
return f"<{self.BUCKET_BOUNDS[0]}ms"
elif idx >= len(self.BUCKET_BOUNDS):
return f">{self.BUCKET_BOUNDS[-1]}ms"
else:
return f"{self.BUCKET_BOUNDS[idx-1]}-{self.BUCKET_BOUNDS[idx]}ms"
def get_percentiles(self) -> PercentileStats:
"""Calculate percentile statistics."""
with self._lock:
if not self._samples:
return PercentileStats(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
sorted_samples = sorted(self._samples)
count = len(sorted_samples)
def percentile(p: float) -> float:
if count == 1:
return sorted_samples[0]
idx = (p / 100) * (count - 1)
lower = int(idx)
upper = lower + 1
if upper >= count:
return sorted_samples[-1]
frac = idx - lower
return sorted_samples[lower] * (1 - frac) + sorted_samples[upper] * frac
mean = self._total / count
variance = sum((x - mean) ** 2 for x in sorted_samples) / count
return PercentileStats(
p50=percentile(50),
p90=percentile(90),
p95=percentile(95),
p99=percentile(99),
p999=percentile(99.9),
min=self._min,
max=self._max,
mean=mean,
std=math.sqrt(variance),
count=count
)
def render_histogram(self, width: int = 60) -> str:
"""Render ASCII histogram."""
with self._lock:
if not self._bucket_counts:
return "No data"
total = sum(self._bucket_counts.values())
max_count = max(self._bucket_counts.values())
lines = [f"\n📊 Latency Histogram: {self.name}\n"]
lines.append("┌" + "─" * (width + 15) + "┐")
for i in range(len(self.BUCKET_BOUNDS) + 1):
count = self._bucket_counts.get(i, 0)
if count == 0 and total > 1000: # Skip empty buckets for large datasets
continue
pct = count / total * 100 if total > 0 else 0
bar_len = int((count / max_count) * width) if max_count > 0 else 0
bar = "█" * bar_len + "░" * (width - bar_len)
label = self._bucket_label(i)
lines.append(f"│ {label:>15} │{bar}│ {count:>6} ({pct:>5.1f}%)")
lines.append("└" + "─" * (width + 15) + "┘")
return "\n".join(lines)
def clear(self) -> None:
"""Clear all recorded data."""
with self._lock:
self._samples.clear()
self._bucket_counts.clear()
self._total = 0.0
self._count = 0
self._min = float('inf')
self._max = 0.0
# ============================================================================
# FLAMEGRAPH GENERATOR
# ============================================================================
class FlamegraphCollector:
"""
Collects stack samples and generates flamegraph data.
Uses statistical sampling for low overhead.
"""
def __init__(self, sample_interval_ms: float = 10.0):
self.sample_interval = sample_interval_ms / 1000.0
self._samples: List[ProfileSample] = []
self._stack_counts: Dict[str, int] = defaultdict(int)
self._running = False
self._thread: Optional[threading.Thread] = None
self._start_time = 0.0
self._lock = threading.Lock()
def start(self) -> None:
"""Start sampling profiler."""
self._running = True
self._start_time = time.time()
self._thread = threading.Thread(target=self._sample_loop, daemon=True)
self._thread.start()
def stop(self) -> None:
"""Stop sampling profiler."""
self._running = False
if self._thread:
self._thread.join(timeout=1.0)
def _sample_loop(self) -> None:
"""Main sampling loop."""
while self._running:
try:
self._collect_sample()
except Exception:
pass
time.sleep(self.sample_interval)
def _collect_sample(self) -> None:
"""Collect a single stack sample from all threads."""
timestamp = time.time()
for thread_id, frame in sys._current_frames().items():
try:
stack = []
current = frame
while current:
func_name = current.f_code.co_name
filename = os.path.basename(current.f_code.co_filename)
line = current.f_lineno
stack.append(f"{filename}:{func_name}:{line}")
current = current.f_back
if stack:
# Reverse to get root at top
stack_key = ";".join(reversed(stack))
with self._lock:
self._stack_counts[stack_key] += 1
self._samples.append(ProfileSample(
timestamp=timestamp,
stack=list(reversed(stack)),
thread_name=f"thread-{thread_id}"
))
except Exception:
pass
def get_flamegraph_data(self) -> Dict[str, Any]:
"""Get data suitable for flamegraph visualization."""
with self._lock:
return {
"stacks": dict(self._stack_counts),
"total_samples": sum(self._stack_counts.values()),
"sample_count": len(self._samples),
"duration_seconds": time.time() - self._start_time
}
def generate_svg_flamegraph(self, output_path: str, title: str = "Flamegraph") -> None:
"""Generate an SVG flamegraph."""
data = self.get_flamegraph_data()
if not data["stacks"]:
return
svg = self._build_svg(data["stacks"], data["total_samples"], title)
with open(output_path, 'w') as f:
f.write(svg)
def _build_svg(self, stacks: Dict[str, int], total: int, title: str) -> str:
"""Build SVG flamegraph from stack data."""
# Parse stacks into tree structure
tree = {}
for stack, count in stacks.items():
parts = stack.split(";")
current = tree
for part in parts:
if part not in current:
current[part] = {"_count": 0, "_children": {}}
current[part]["_count"] += count
current = current[part]["_children"]
# SVG parameters
width = 1200
height = 600
row_height = 20
font_size = 12
# Build SVG
lines = [
f'<?xml version="1.0" encoding="UTF-8"?>',
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
f'<style>',
f' .flamebox {{ fill: rgb(255, 255, 255); }}',
f' .flamefunc {{ font-family: monospace; font-size: {font_size}px; }}',
f' .flametitle {{ font-family: sans-serif; font-size: 16px; font-weight: bold; }}',
f'</style>',
f'<rect class="flamebox" width="100%" height="100%"/>',
f'<text class="flametitle" x="10" y="25">{title} ({total} samples)</text>',
]
def render_level(node: dict, x: float, y: int, available_width: float) -> None:
"""Recursively render flamegraph levels."""
if y > height - row_height:
return
items = sorted(node.items(), key=lambda x: x[1].get("_count", 0), reverse=True)
current_x = x
for name, data in items:
if name.startswith("_"):
continue
count = data.get("_count", 0)
if count == 0:
continue
# Calculate width based on sample proportion
item_width = (count / total) * available_width
if item_width < 1:
continue
# Color based on depth
depth = y // row_height
hue = (depth * 30) % 360
saturation = 70 + (depth * 2) % 20
lightness = 50 + (depth * 3) % 15
color = f"hsl({hue}, {saturation}%, {lightness}%)"
# Draw rectangle
lines.append(
f'<rect x="{current_x:.1f}" y="{y}" '
f'width="{item_width:.1f}" height="{row_height - 1}" '
f'fill="{color}" stroke="white" stroke-width="0.5">'
f'<title>{name} ({count} samples, {count/total*100:.1f}%)</title>'
f'</rect>'
)
# Draw text if wide enough
if item_width > 40:
text = name[:int(item_width / 7)]
lines.append(
f'<text class="flamefunc" x="{current_x + 3}" y="{y + 14}" '
f'fill="black" clip-path="url(#clip-{current_x:.0f})">{text}</text>'
)
# Recurse for children
children = data.get("_children", {})
if children:
render_level(children, current_x, y + row_height, item_width)
current_x += item_width
# Start rendering from root
render_level(tree, 10, 40, width - 20)
lines.append('</svg>')
return '\n'.join(lines)
def render_text_flamegraph(self, top_n: int = 20) -> str:
"""Render a text-based flamegraph summary."""
data = self.get_flamegraph_data()
if not data["stacks"]:
return "No samples collected"
lines = [f"\n🔥 Flamegraph Summary ({data['total_samples']} samples)\n"]
lines.append("Top stack traces by sample count:")
lines.append("─" * 80)
sorted_stacks = sorted(data["stacks"].items(), key=lambda x: x[1], reverse=True)[:top_n]
for i, (stack, count) in enumerate(sorted_stacks, 1):
pct = count / data["total_samples"] * 100
bar = "█" * int(pct / 2)
parts = stack.split(";")
lines.append(f"\n{i}. {count} samples ({pct:.1f}%) {bar}")
for j, part in enumerate(parts[-5:]): # Show last 5 frames
indent = " " * j
lines.append(f"{indent}└─ {part}")
return "\n".join(lines)
def clear(self) -> None:
"""Clear collected samples."""
with self._lock:
self._samples.clear()
self._stack_counts.clear()
# ============================================================================
# ALLOCATION TRACER
# ============================================================================
class AllocationTracer:
"""
Memory allocation tracer using tracemalloc.
Tracks allocations by traceback with statistics.
"""
def __init__(self, nframe: int = 25):
self.nframe = nframe
self._snapshots: List[tracemalloc.Snapshot] = []
self._peak_memory = 0
self._start_time: Optional[float] = None
self._lock = threading.Lock()
def start(self) -> None:
"""Start allocation tracing."""
if not tracemalloc.is_tracing():
tracemalloc.start(self.nframe)
self._start_time = time.time()
self._snapshots = [tracemalloc.take_snapshot()]
def stop(self) -> None:
"""Stop allocation tracing."""
if tracemalloc.is_tracing():
self._snapshots.append(tracemalloc.take_snapshot())
self._peak_memory = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
def take_snapshot(self) -> None:
"""Take intermediate snapshot."""
if tracemalloc.is_tracing():
with self._lock:
self._snapshots.append(tracemalloc.take_snapshot())
def get_allocation_stats(self, limit: int = 10) -> List[Dict[str, Any]]:
"""Get allocation statistics by traceback."""
if len(self._snapshots) < 2:
return []
stats = self._snapshots[-1].statistics('traceback')
results = []
for stat in stats[:limit]:
traceback_lines = []
for frame in stat.traceback:
traceback_lines.append(f"{frame.filename}:{frame.lineno} in {frame.name}")
results.append({
"size_bytes": stat.size,
"size_human": self._format_bytes(stat.size),
"count": stat.count,
"traceback": traceback_lines
})
return results
def get_memory_diff(self) -> Dict[str, Any]:
"""Get memory difference between snapshots."""
if len(self._snapshots) < 2:
return {"error": "Need at least 2 snapshots"}
old_stats = self._snapshots[0].statistics('lineno')
new_stats = self._snapshots[-1].statistics('lineno')
diff = tracemalloc.compare_snapshots([self._snapshots[0], self._snapshots[-1]])
return {
"peak_memory": self._format_bytes(self._peak_memory),
"current_memory": self._format_bytes(tracemalloc.get_traced_memory()[0]),
"top_increases": [
{
"file": stat[0],
"size_diff": self._format_bytes(stat[1].size_diff),
"count_diff": stat[1].count_diff
}
for stat in diff[:10]
]
}
def _format_bytes(self, size: int) -> str:
"""Format bytes as human readable string."""
for unit in ['B', 'KB', 'MB', 'GB']:
if abs(size) < 1024:
return f"{size:.1f}{unit}"
size /= 1024
return f"{size:.1f}TB"
def render_allocation_report(self, limit: int = 15) -> str:
"""Render text allocation report."""
stats = self.get_allocation_stats(limit)
if not stats:
return "No allocation data available"
lines = ["\n💾 Memory Allocation Report\n"]
lines.append("┌" + "─" * 78 + "┐")
lines.append(f"│ {'Location':<40} │ {'Size':>12} │ {'Count':>8} │")
lines.append("├" + "─" * 78 + "┤")
for stat in stats:
if stat["traceback"]:
location = stat["traceback"][0][:40]
else:
location = "<unknown>"
lines.append(f"│ {location:<40} │ {stat['size_human']:>12} │ {stat['count']:>8} │")
lines.append("└" + "─" * 78 + "┘")
# Add traceback details for top allocator
if stats:
lines.append(f"\n📍 Top allocation traceback:")
for i, line in enumerate(stats[0]["traceback"][:5]):
indent = " " * i
lines.append(f"{indent}└─ {line}")
return "\n".join(lines)
# ============================================================================
# REGRESSION GUARD
# ============================================================================
class RegressionGuard:
"""
Performance regression detection with baseline comparison.
Stores baselines and alerts on significant changes.
"""
def __init__(self, baseline_dir: str = ".perf_baselines"):
self.baseline_dir = Path(baseline_dir)
self.baseline_dir.mkdir(exist_ok=True)
self._thresholds: Dict[str, Dict[str, float]] = {}
self._results: List[RegressionResult] = []
def set_threshold(self, metric_name: str, warning_pct: float = 10.0,
critical_pct: float = 25.0) -> None:
"""Set regression thresholds for a metric."""
self._thresholds[metric_name] = {
"warning": warning_pct,
"critical": critical_pct
}
def save_baseline(self, metric_name: str, value: float,
metadata: Optional[Dict] = None) -> None:
"""Save a baseline value for comparison."""
baseline = {
"value": value,
"timestamp": datetime.now().isoformat(),
"metadata": metadata or {}
}
baseline_path = self.baseline_dir / f"{metric_name}.json"
with open(baseline_path, 'w') as f:
json.dump(baseline, f, indent=2)
def load_baseline(self, metric_name: str) -> Optional[Dict]:
"""Load baseline value for a metric."""
baseline_path = self.baseline_dir / f"{metric_name}.json"
if baseline_path.exists():
with open(baseline_path) as f:
return json.load(f)
return None
def check_regression(self, metric_name: str, current_value: float) -> RegressionResult:
"""Check if current value represents a regression."""
baseline = self.load_baseline(metric_name)
if not baseline:
return RegressionResult(
metric_name=metric_name,
baseline_value=0,
current_value=current_value,
change_percent=0,
threshold_percent=0,
is_regression=False,
severity="none"
)
baseline_value = baseline["value"]
if baseline_value == 0:
change_pct = 0 if current_value == 0 else 100
else:
change_pct = ((current_value - baseline_value) / baseline_value) * 100
thresholds = self._thresholds.get(metric_name, {"warning": 10, "critical": 25})
# For latency, increase is regression; for throughput, decrease is regression
is_regression = abs(change_pct) > thresholds["warning"]
if abs(change_pct) > thresholds["critical"]:
severity = "critical"
elif abs(change_pct) > thresholds["warning"]:
severity = "warning"
else:
severity = "none"
result = RegressionResult(
metric_name=metric_name,
baseline_value=baseline_value,
current_value=current_value,
change_percent=change_pct,
threshold_percent=thresholds["warning"],
is_regression=is_regression,
severity=severity
)
self._results.append(result)
return result
def check_histogram_regression(self, histogram: LatencyHistogram,
metric_prefix: str = "") -> Dict[str, RegressionResult]:
"""Check regression for all histogram percentiles."""
stats = histogram.get_percentiles()
results = {}
percentiles = [
("p50", stats.p50),
("p90", stats.p90),
("p95", stats.p95),
("p99", stats.p99),
("mean", stats.mean)
]
for name, value in percentiles:
metric_name = f"{metric_prefix}_{name}" if metric_prefix else name
results[name] = self.check_regression(metric_name, value)
return results
def render_report(self) -> str:
"""Render regression report."""
if not self._results:
return "No regression checks performed"
lines = ["\n🛡️ Regression Guard Report\n"]
lines.append("┌" + "─" * 88 + "┐")
lines.append(f"│ {'Metric':<25} │ {'Baseline':>12} │ {'Current':>12} │ {'Change':>10} │ {'Status':<10} │")
lines.append("├" + "─" * 88 + "┤")
for result in self._results:
if result.severity == "critical":
status = "🔴 CRITICAL"
elif result.severity == "warning":
status = "🟡 WARNING"
else:
status = "✅ OK"
change = f"{result.change_percent:+.1f}%"
lines.append(
f"│ {result.metric_name:<25} │ {result.baseline_value:>12.3f} │ "
f"{result.current_value:>12.3f} │ {change:>10} │ {status:<10} │"
)
lines.append("└" + "─" * 88 + "┘")
regressions = [r for r in self._results if r.is_regression]
if regressions:
lines.append(f"\n⚠️ {len(regressions)} potential regression(s) detected!")
else:
lines.append("\n✅ No regressions detected")
return "\n".join(lines)
# ============================================================================
# PROFILING CONTEXT MANAGERS AND DECORATORS
# ============================================================================
class Profiler:
"""
Main profiler class combining all profiling capabilities.
"""
def __init__(self, name: str = "profile"):
self.name = name
self.histograms: Dict[str, LatencyHistogram] = {}
self.flamegraph = FlamegraphCollector()
self.allocations = AllocationTracer()
self.regression_guard = RegressionGuard()
self._enabled = True
def enable(self) -> None:
"""Enable profiling."""
self._enabled = True
def disable(self) -> None:
"""Disable profiling."""
self._enabled = False
def histogram(self, name: str) -> LatencyHistogram:
"""Get or create a latency histogram."""
if name not in self.histograms:
self.histograms[name] = LatencyHistogram(name)
return self.histograms[name]
@contextmanager
def measure(self, operation: str, metadata: Optional[Dict] = None):
"""Context manager to measure operation latency."""
if not self._enabled:
yield
return
hist = self.histogram(operation)
start = time.perf_counter()
success = True
try:
yield
except Exception:
success = False
raise
finally:
duration = (time.perf_counter() - start) * 1000 # Convert to ms
hist.record(duration)
def profile(self, func: Callable[..., T]) -> Callable[..., T]:
"""Decorator to profile a function."""
@functools.wraps(func)
def wrapper(*args, **kwargs) -> T:
if not self._enabled:
return func(*args, **kwargs)
with self.measure(func.__name__):
return func(*args, **kwargs)
return wrapper
def start_all(self) -> None:
"""Start all profilers."""
self.flamegraph.start()
self.allocations.start()
def stop_all(self) -> None:
"""Stop all profilers."""
self.flamegraph.stop()
self.allocations.stop()
def full_report(self) -> str:
"""Generate full profiling report."""
lines = [
"\n" + "=" * 80,
f"📊 PERFORMANCE PROFILING REPORT: {self.name}",
"=" * 80,
]
# Latency histograms
for name, hist in self.histograms.items():
stats = hist.get_percentiles()
lines.append(f"\n📈 Latency Stats: {name}")
lines.append("─" * 40)
lines.append(f" Count: {stats.count:,}")
lines.append(f" Mean: {stats.mean:.3f}ms")
lines.append(f" Std: {stats.std:.3f}ms")
lines.append(f" Min: {stats.min:.3f}ms")
lines.append(f" Max: {stats.max:.3f}ms")
lines.append("─" * 40)
lines.append(f" P50: {stats.p50:.3f}ms")
lines.append(f" P90: {stats.p90:.3f}ms")
lines.append(f" P95: {stats.p95:.3f}ms")
lines.append(f" P99: {stats.p99:.3f}ms")
lines.append(f" P99.9: {stats.p999:.3f}ms")
lines.append(hist.render_histogram(40))
# Flamegraph summary
lines.append(self.flamegraph.render_text_flamegraph())
# Allocation report
lines.append(self.allocations.render_allocation_report())
return "\n".join(lines)
# Global profiler instance
_global_profiler: Optional[Profiler] = None
_profiler_lock = threading.Lock()
def get_profiler(name: str = "global") -> Profiler:
"""Get the global profiler instance."""
global _global_profiler
with _profiler_lock:
if _global_profiler is None:
_global_profiler = Profiler(name)
return _global_profiler
def measure(operation: str, metadata: Optional[Dict] = None):
"""Context manager using global profiler."""
return get_profiler().measure(operation, metadata)
def profile(func: Callable[..., T]) -> Callable[..., T]:
"""Decorator using global profiler."""
return get_profiler().profile(func)
# ============================================================================
# DEMO / TEST WORKLOADS
# ============================================================================
def cpu_intensive_work(n: int = 100000) -> int:
"""Simulate CPU-intensive work."""
result = 0
for i in range(n):
result += math.sqrt(i) * math.sin(i)
return int(result)
def memory_intensive_work(size_kb: int = 100) -> bytes:
"""Simulate memory-intensive work."""
data = bytearray(size_kb * 1024)
for i in range(0, len(data), 4096):
data[i] = random.randint(0, 255)
return bytes(data)
def io_simulated_work(delay_ms: float = 10) -> None:
"""Simulate I/O wait."""
time.sleep(delay_ms / 1000)
@profile
def mixed_workload(iterations: int = 100) -> Dict[str, Any]:
"""Mixed workload for demonstration."""
results = []
for i in range(iterations):
# CPU work
with measure("cpu_work"):
cpu_result = cpu_intensive_work(random.randint(1000, 50000))
# Memory work
with measure("memory_work"):
mem_result = memory_intensive_work(random.randint(10, 500))
# Simulated I/O
with measure("io_work"):
io_simulated_work(random.uniform(1, 20))
results.append({"cpu": cpu_result, "mem_len": len(mem_result)})
return {"iterations": iterations, "results": results}
# ============================================================================
# MAIN CLI
# ============================================================================
def run_demo():
"""Run profiling demonstration."""
if RICH_AVAILABLE:
console = Console()
console.print(Panel.fit(
"[bold blue]Performance Profiling Toolkit Demo[/bold blue]",
subtitle="Flamegraphs • P95/P99 • Allocations • Regression Guards"
))
else:
print("\n=== Performance Profiling Toolkit Demo ===\n")
profiler = Profiler("demo")
# Set up regression thresholds
profiler.regression_guard.set_threshold("demo_cpu_work_p95", warning_pct=15, critical_pct=30)
profiler.regression_guard.set_threshold("demo_io_work_p99", warning_pct=20, critical_pct=40)
# Optionally save baselines (uncomment to set initial baseline)
# profiler.regression_guard.save_baseline("demo_cpu_work_p95", 1.5)
# profiler.regression_guard.save_baseline("demo_io_work_p99", 15.0)
print("🚀 Starting comprehensive profiling session...")
print(" Collecting: flamegraph samples, allocation data, latency metrics\n")
# Start all profilers
profiler.start_all()
# Run measured workloads
print("📊 Running mixed workload (100 iterations)...")
for batch in range(3):
print(f" Batch {batch + 1}/3...", end="", flush=True)
for i in range(33):
# Measure different operation types
with profiler.measure("fast_operation"):
_ = sum(range(100))
with profiler.measure("medium_operation"):
cpu_intensive_work(5000)
with profiler.measure("slow_operation"):
io_simulated_work(random.uniform(5, 15))
with profiler.measure("allocating_operation"):
memory_intensive_work(random.randint(50, 200))
print(" done")
# Stop profilers
profiler.stop_all()
# Generate reports
print("\n" + profiler.full_report())
# Check for regressions
print("\n🔍 Checking for performance regressions...")
for name, hist in profiler.histograms.items():
stats = hist.get_percentiles()
if stats.count > 0:
profiler.regression_guard.check_regression(f"demo_{name}_p95", stats.p95)
profiler.regression_guard.check_regression(f"demo_{name}_p99", stats.p99)
print(profiler.regression_guard.render_report())
# Generate flamegraph
flamegraph_path = "flamegraph_demo.svg"
profiler.flamegraph.generate_svg_flamegraph(flamegraph_path, "Demo Flamegraph")
print(f"\n🔥 Flamegraph saved to: {flamegraph_path}")
# Save performance report
report_path = "performance_report.json"
report_data = {
"timestamp": datetime.now().isoformat(),
"histograms": {
name: {
"p50": hist.get_percentiles().p50,
"p90": hist.get_percentiles().p90,
"p95": hist.get_percentiles().p95,
"p99": hist.get_percentiles().p99,
"mean": hist.get_percentiles().mean,
"count": hist.get_percentiles().count
}
for name, hist in profiler.histograms.items()
},
"flamegraph": profiler.flamegraph.get_flamegraph_data(),
"memory": profiler.allocations.get_memory_diff()
}
with open(report_path, 'w') as f:
json.dump(report_data, f, indent=2)
print(f"📄 Full report saved to: {report_path}")
if __name__ == "__main__":
run_demo()
Output Example
================================================================================
📊 PERFORMANCE PROFILING REPORT: demo
================================================================================
📈 Latency Stats: fast_operation
────────────────────────────────────────
Count: 99
Mean: 0.004ms
Std: 0.002ms
Min: 0.001ms
Max: 0.015ms
────────────────────────────────────────
P50: 0.004ms
P90: 0.006ms
P95: 0.007ms
P99: 0.012ms
P99.9: 0.015ms
📊 Latency Histogram: fast_operation
┌──────────────────────────────────────────────────────────────────┐
│ <0.1ms │████████████████████████████████████████████████│ 99 (100.0%)
└──────────────────────────────────────────────────────────────────┘
🔥 Flamegraph Summary (1500 samples)
Top stack traces by sample count:
────────────────────────────────────────
1. 450 samples (30.0%) ███████████████
└─ profiling.py:cpu_intensive_work:385
└─ profiling.py:measure:285
└─ profiling.py:run_demo:456
💾 Memory Allocation Report
┌──────────────────────────────────────────────────────────────────────────────┐
│ Location │ Size │ Count │
├──────────────────────────────────────────────────────────────────────────────┤
│ profiling.py:memory_intensive_work:390 │ 15.2MB │ 150 │
│ profiling.py:cpu_intensive_work:385 │ 2.1MB │ 300 │
└──────────────────────────────────────────────────────────────────────────────┘
🛡️ Regression Guard Report
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ Metric │ Baseline │ Current │ Change │ Status │
├────────────────────────────────────────────────────────────────────────────────────────┤
│ demo_fast_operation_p95 │ 0.005 │ 0.007 │ +40.0% │ 🟡 WARNING│
│ demo_medium_operation_p99 │ 2.100 │ 2.350 │ +11.9% │ ✅ OK │
└────────────────────────────────────────────────────────────────────────────────────────┘
🔥 Flamegraph saved to: flamegraph_demo.svg
📄 Full report saved to: performance_report.json
Key Features
| Feature | Description |
|---|
| Flamegraphs | Stack sampling profiler with SVG generation |
| P95/P99 Metrics | Bucketed histograms with percentile calculations |
| Allocation Tracing | Memory tracking with traceback attribution |
| Regression Guards | Baseline comparison with configurable thresholds |
| Low Overhead | Statistical sampling with minimal runtime impact |
| Thread Safe | All components are thread-safe for concurrent use |
| Rich Output | Beautiful terminal output and JSON reports |