nlsq.profiler module¶
Performance Profiling for NLSQ¶
Comprehensive performance profiling system for tracking and analyzing optimization performance metrics.
- class nlsq.utils.profiler.PerformanceProfiler[source]
Bases:
objectPerformance profiler for NLSQ optimization.
Tracks and analyzes performance metrics across optimization runs.
Examples
>>> profiler = PerformanceProfiler() >>> with profiler.profile("my_optimization"): ... result = curve_fit(model, x, y, p0=[1, 2]) >>> >>> report = profiler.get_report() >>> print(report)
- __init__()[source]
Initialize performance profiler.
- profiles: dict[str, list[ProfileMetrics]]
- start_profile(name='default')[source]
Start profiling a new optimization run.
- Parameters:
name (str) – Name for this profiling session
- Returns:
metrics – Metrics object for this profile
- Return type:
- end_profile(metrics=None)[source]
End current profiling session.
- Parameters:
metrics (ProfileMetrics, optional) – Metrics to finalize. If None, uses current profile.
- profile(name='default')[source]
Context manager for profiling.
- Parameters:
name (str) – Name for this profiling session
Examples
>>> profiler = PerformanceProfiler() >>> with profiler.profile("test_1"): ... result = curve_fit(model, x, y)
- record_timing(category, duration)[source]
Record timing for a specific category.
- update_current(**kwargs)[source]
Update current profile with arbitrary metrics.
- Parameters:
**kwargs – Metrics to update
- get_metrics(name='default')[source]
Get all metrics for a named profile.
- Parameters:
name (str) – Profile name
- Returns:
metrics – All metrics for this profile
- Return type:
- get_summary(name='default')[source]
Get summary statistics for a named profile.
- get_report(name='default', detailed=False)[source]
Generate a formatted performance report.
- compare_profiles(name1, name2)[source]
Compare two profiling sessions.
- class nlsq.utils.profiler.ProfileMetrics(total_time=0.0, jit_compile_time=0.0, optimization_time=0.0, jacobian_time=0.0, n_iterations=0, n_function_evals=0, n_jacobian_evals=0, n_data_points=0, n_parameters=0, data_dimension=1, final_cost=0.0, initial_cost=0.0, cost_reduction=0.0, final_gradient_norm=0.0, success=False, method='', backend='cpu', metadata=<factory>)[source]
Bases:
objectContainer for performance metrics from a single optimization run.
- total_time: float
- jit_compile_time: float
- optimization_time: float
- jacobian_time: float
- n_iterations: int
- n_function_evals: int
- n_jacobian_evals: int
- n_data_points: int
- n_parameters: int
- data_dimension: int
- final_cost: float
- initial_cost: float
- cost_reduction: float
- final_gradient_norm: float
- success: bool
- method: str
- backend: str
- metadata: dict
- speedup_vs_scipy()[source]
Estimate speedup vs SciPy (rough heuristic).
- iterations_per_second()[source]
Calculate iterations per second.
- function_evals_per_second()[source]
Calculate function evaluations per second.
- to_dict()[source]
Convert to dictionary.
- __init__(total_time=0.0, jit_compile_time=0.0, optimization_time=0.0, jacobian_time=0.0, n_iterations=0, n_function_evals=0, n_jacobian_evals=0, n_data_points=0, n_parameters=0, data_dimension=1, final_cost=0.0, initial_cost=0.0, cost_reduction=0.0, final_gradient_norm=0.0, success=False, method='', backend='cpu', metadata=<factory>)
- nlsq.utils.profiler.clear_profiling_data()[source]
Clear all global profiling data.
- nlsq.utils.profiler.get_global_profiler()[source]
Get the global profiler instance.
- Returns:
profiler – Global profiler
- Return type:
Overview¶
The profiler module provides performance profiling utilities for NLSQ optimization workflows.
Key Features¶
Function-level profiling for optimization steps
Memory profiling to track allocation patterns
Timing statistics for performance analysis
Integration with JAX profiler
Classes¶
Example Usage¶
from nlsq.utils.profiler import Profiler
from nlsq import curve_fit
import jax.numpy as jnp
# Create profiler
profiler = Profiler(enable=True)
# Profile curve fitting
def model(x, a, b):
return a * jnp.exp(-b * x)
x = jnp.linspace(0, 10, 1000)
y = 2.5 * jnp.exp(-0.5 * x)
with profiler.profile("curve_fit"):
popt, pcov = curve_fit(model, x, y, p0=[1.0, 0.1])
# Get profiling results
results = profiler.get_results()
print(f"Total time: {results['curve_fit']['total_time']:.3f} s")
print(f"Call count: {results['curve_fit']['call_count']}")
Performance Analysis¶
# Detailed profiling with memory tracking
profiler = Profiler(enable=True, track_memory=True)
with profiler.profile("optimization"):
result = expensive_operation()
# Get detailed statistics
stats = profiler.get_detailed_stats()
print(f"Peak memory: {stats['peak_memory_mb']:.2f} MB")
print(f"Average time: {stats['avg_time']:.3f} s")
See Also¶
nlsq.profiling module - Transfer profiling utilities
nlsq.diagnostics package - Optimization diagnostics
NLSQ Performance Tuning Guide - Performance tuning guide