1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! # Comprehensive Performance Analysis Framework for Sparse Tensors
//!
//! This module provides a complete suite of performance analysis, benchmarking, and optimization
//! tools specifically designed for sparse tensor operations. The framework is organized into
//! specialized modules that work together to deliver comprehensive performance insights.
//!
//! ## Architecture Overview
//!
//! The performance analysis system is built around four core modules:
//!
//! - **core**: Fundamental types and utilities for measurements and timing
//! - **benchmarking**: Comprehensive profiling tools for sparse operations
//! - **memory_analysis**: Memory usage analysis and reporting capabilities
//! - **auto_tuning**: Intelligent format selection and optimization
//!
//! ## Quick Start
//!
//! ### Basic Performance Profiling
//!
//! ```rust
//! use torsh_sparse::performance::{SparseProfiler, BenchmarkConfig};
//! use torsh_sparse::{CooTensor, SparseFormat};
//! use torsh_core::Shape;
//!
//! // Create a profiler with fast benchmark configuration
//! let mut profiler = SparseProfiler::new(BenchmarkConfig::fast());
//!
//! // Create a test sparse tensor
//! let rows = vec![0, 0, 1, 2];
//! let cols = vec![0, 2, 1, 2];
//! let vals = vec![1.0, 2.0, 3.0, 4.0];
//! let shape = Shape::new(vec![3, 3]);
//! let coo = CooTensor::new(rows, cols, vals, shape)?;
//!
//! // Benchmark format conversion
//! let measurement = profiler.benchmark_format_conversion(&coo, SparseFormat::Csr)?;
//! println!("Conversion took: {:?}", measurement.duration);
//! ```
//!
//! ### Memory Analysis
//!
//! ```rust
//! use torsh_sparse::performance::MemoryAnalysis;
//! use torsh_sparse::SparseFormat;
//!
//! // Analyze memory usage for different formats
//! let coo_analysis = MemoryAnalysis::new(SparseFormat::Coo, 1000, (100, 100));
//! let csr_analysis = MemoryAnalysis::new(SparseFormat::Csr, 1000, (100, 100));
//!
//! println!("COO compression ratio: {:.2}x", coo_analysis.compression_ratio);
//! println!("CSR compression ratio: {:.2}x", csr_analysis.compression_ratio);
//!
//! let comparison = coo_analysis.compare_with(&csr_analysis);
//! println!("Better format: {:?}", comparison.better_format);
//! ```
//!
//! ### Auto-Tuning
//!
//! ```rust
//! use torsh_sparse::performance::AutoTuner;
//! use torsh_tensor::Tensor;
//!
//! let mut tuner = AutoTuner::new();
//! let dense = Tensor::randn(&[1000, 1000])?;
//!
//! // Automatically find optimal format for matrix multiplication
//! let optimal_format = tuner.find_optimal_format(&dense, "matmul", 1e-6)?;
//! println!("Optimal format: {:?}", optimal_format);
//!
//! // Get performance recommendations
//! let recommendations = tuner.get_recommendations();
//! for rec in recommendations {
//! println!("Recommendation: {}", rec);
//! }
//! ```
//!
//! ### Comprehensive Performance Report
//!
//! ```rust
//! use torsh_sparse::performance::{SparseProfiler, PerformanceReport};
//!
//! let mut profiler = SparseProfiler::new(BenchmarkConfig::default());
//!
//! // Run multiple benchmarks...
//! // profiler.benchmark_*(...);
//!
//! // Generate comprehensive report
//! let report = profiler.generate_report();
//! println!("{}", report);
//!
//! // Find optimal operations
//! if let Some(fastest) = report.find_fastest_operation("conversion") {
//! println!("Fastest conversion: {}", fastest.operation);
//! }
//! ```
//!
//! ## Performance Optimization Guidelines
//!
//! ### Format Selection
//!
//! | Use Case | Recommended Format | Rationale |
//! |----------|-------------------|-----------|
//! | Matrix multiplication | CSR | Efficient row access patterns |
//! | Transpose operations | CSC | Efficient column access patterns |
//! | Construction/modification | COO | Simple triplet format |
//! | Memory-constrained | Auto-tune | Let the system decide |
//!
//! ### Benchmarking Best Practices
//!
//! 1. **Warm-up iterations**: Always include warm-up runs to account for JIT compilation
//! 2. **Multiple measurements**: Use statistical analysis across multiple runs
//! 3. **Memory tracking**: Enable memory collection for comprehensive analysis
//! 4. **Realistic data**: Use representative matrix sizes and sparsity patterns
//! 5. **Operation context**: Consider the full operation pipeline, not just individual ops
//!
//! ### Auto-Tuning Configuration
//!
//! Choose the appropriate tuning configuration based on your use case:
//!
//! - **Conservative**: Thorough benchmarking with high confidence thresholds
//! - **Aggressive**: Fast tuning with lower improvement thresholds
//! - **Custom**: Tailored configuration for specific workloads
//!
//! ## Advanced Features
//!
//! ### Custom Metrics
//!
//! The performance framework supports custom metrics for domain-specific analysis:
//!
//! ```rust
//! use torsh_sparse::performance::PerformanceMeasurement;
//! use std::collections::HashMap;
//!
//! let mut measurement = PerformanceMeasurement::new("custom_op".to_string());
//! measurement.add_metric("flops".to_string(), 1000000.0);
//! measurement.add_metric("efficiency".to_string(), 0.85);
//!
//! if let Some(ops_per_sec) = measurement.ops_per_second() {
//! println!("Operations per second: {:.2}", ops_per_sec);
//! }
//! ```
//!
//! ### Memory Efficiency Analysis
//!
//! ```rust
//! use torsh_sparse::performance::MemoryAnalysis;
//!
//! let analysis = MemoryAnalysis::new(format, nnz, (rows, cols));
//!
//! println!("Memory efficiency: {:.2}%", analysis.memory_efficiency() * 100.0);
//! println!("Sparsity level: {:.2}%", analysis.sparsity_level() * 100.0);
//! println!("Efficiently compressed: {}", analysis.is_efficiently_compressed());
//! ```
//!
//! ## Integration with Sparse Tensor Operations
//!
//! The performance framework integrates seamlessly with sparse tensor operations:
//!
//! ```rust
//! use torsh_sparse::performance::{AutoTuner, SparseProfiler};
//! use torsh_sparse::{SparseTensor, SparseFormat};
//!
//! // Auto-tune format for specific operation
//! let mut tuner = AutoTuner::new();
//! let optimal_format = tuner.find_optimal_format(&dense_matrix, "matmul", 1e-6)?;
//!
//! // Convert to optimal format
//! let sparse = match optimal_format {
//! SparseFormat::Coo => dense_matrix.to_sparse_coo(1e-6)?,
//! SparseFormat::Csr => dense_matrix.to_sparse_csr(1e-6)?,
//! SparseFormat::Csc => dense_matrix.to_sparse_csc(1e-6)?,
//! };
//!
//! // Profile the actual operation
//! let mut profiler = SparseProfiler::new(BenchmarkConfig::default());
//! let measurement = profiler.benchmark_sparse_matmul(&sparse, &other_sparse)?;
//! ```
//!
//! ## Thread Safety and Concurrency
//!
//! All performance analysis tools are designed to be thread-safe where appropriate:
//!
//! - **PerformanceMeasurement**: Immutable after creation, safe to share
//! - **BenchmarkConfig**: Read-only configuration, safe to share
//! - **MemoryAnalysis**: Immutable analysis results, safe to share
//! - **SparseProfiler**: Not thread-safe, use separate instances per thread
//! - **AutoTuner**: Contains mutable cache, requires synchronization for concurrent access
// Core module exports
// Re-export core types and utilities
pub use ;
// Re-export benchmarking functionality
pub use SparseProfiler;
// Re-export memory analysis types
pub use ;
// Re-export auto-tuning capabilities
pub use ;
/// Convenience function to create a comprehensive performance analyzer
///
/// Creates a fully configured performance analysis setup with sensible defaults
/// for most use cases. This includes a profiler, auto-tuner, and report generator.
///
/// # Examples
///
/// ```rust
/// use torsh_sparse::performance::create_performance_analyzer;
///
/// let (mut profiler, mut tuner) = create_performance_analyzer();
///
/// // Use profiler for detailed benchmarking
/// // Use tuner for automatic format optimization
/// ```
/// Convenience function to create a fast performance analyzer for quick analysis
///
/// Uses fast benchmark configurations suitable for development and quick testing.
///
/// # Examples
///
/// ```rust
/// use torsh_sparse::performance::create_fast_analyzer;
///
/// let (mut profiler, mut tuner) = create_fast_analyzer();
/// // Performs faster but less comprehensive analysis
/// ```
/// Convenience function to create a comprehensive performance analyzer
///
/// Uses thorough benchmark configurations suitable for production optimization
/// and detailed performance analysis.
///
/// # Examples
///
/// ```rust
/// use torsh_sparse::performance::create_comprehensive_analyzer;
///
/// let (mut profiler, mut tuner) = create_comprehensive_analyzer();
/// // Performs thorough but slower analysis
/// ```
/// Analyze memory usage for a specific sparse format and matrix characteristics
///
/// This is a convenience function for quick memory analysis without setting up
/// the full performance framework.
///
/// # Examples
///
/// ```rust
/// use torsh_sparse::performance::analyze_memory_usage;
/// use torsh_sparse::SparseFormat;
///
/// let analysis = analyze_memory_usage(SparseFormat::Csr, 10000, (1000, 1000));
/// println!("Compression ratio: {:.2}x", analysis.compression_ratio);
/// ```
/// Compare memory usage between different sparse formats
///
/// Convenience function to quickly compare memory characteristics of different
/// sparse formats for the same matrix.
///
/// # Examples
///
/// ```rust
/// use torsh_sparse::performance::compare_format_memory;
/// use torsh_sparse::SparseFormat;
///
/// let comparison = compare_format_memory(
/// SparseFormat::Coo,
/// SparseFormat::Csr,
/// 1000,
/// (100, 100)
/// );
///
/// println!("Better format: {:?}", comparison.better_format);
/// ```