sklears-core 0.1.1

Core traits, types, and utilities for sklears machine learning library
Documentation
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! # Advanced Performance Profiling and Optimization Framework
//!
//! This module provides comprehensive performance profiling, analysis, and optimization
//! capabilities for machine learning algorithms. It enables detailed performance
//! measurement, bottleneck identification, and automated optimization suggestions.
//!
//! ## Key Features
//!
//! - **Micro-Benchmarking**: Fine-grained performance measurement
//! - **Hotspot Detection**: Identify performance bottlenecks
//! - **Memory Profiling**: Track memory allocations and usage patterns
//! - **Cache Analysis**: Measure cache hit rates and memory access patterns
//! - **SIMD Utilization**: Analyze vectorization opportunities
//! - **Flamegraph Generation**: Visualize execution profiles
//! - **Optimization Recommendations**: Automated suggestions for improvements
//! - **Cross-Platform Profiling**: Consistent profiling across targets
//!
//! ## Usage
//!
//! ```rust,ignore
//! use sklears_core::performance_profiling::*;
//!
//! // Profile an algorithm
//! let profiler = PerformanceProfiler::new();
//! let profile = profiler.profile(|| {
//!     // Your ML algorithm here
//!     train_model(&data);
//! })?;
//!
//! // Analyze bottlenecks
//! let analysis = profile.analyze_bottlenecks()?;
//! for bottleneck in &analysis.hotspots {
//!     println!("Hotspot: {} ({:.2}% of total time)",
//!              bottleneck.location,
//!              bottleneck.time_percentage);
//! }
//!
//! // Get optimization recommendations
//! let recommendations = profile.get_optimization_recommendations()?;
//! ```

use crate::error::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, Instant};

// =============================================================================
// Core Performance Profiling System
// =============================================================================

/// Main performance profiler for ML algorithms
#[derive(Debug)]
pub struct PerformanceProfiler {
    /// Configuration settings
    #[allow(dead_code)] // intentionally deferred: config accessor not yet exposed
    config: ProfilerConfig,
    /// Performance counters
    counters: PerformanceCounters,
    /// Memory tracker
    memory_tracker: MemoryTracker,
    /// Cache analyzer
    cache_analyzer: CacheAnalyzer,
    /// Execution timeline
    timeline: ExecutionTimeline,
}

impl PerformanceProfiler {
    /// Create a new performance profiler
    pub fn new() -> Self {
        Self {
            config: ProfilerConfig::default(),
            counters: PerformanceCounters::new(),
            memory_tracker: MemoryTracker::new(),
            cache_analyzer: CacheAnalyzer::new(),
            timeline: ExecutionTimeline::new(),
        }
    }

    /// Create profiler with custom configuration
    pub fn with_config(config: ProfilerConfig) -> Self {
        Self {
            config,
            counters: PerformanceCounters::new(),
            memory_tracker: MemoryTracker::new(),
            cache_analyzer: CacheAnalyzer::new(),
            timeline: ExecutionTimeline::new(),
        }
    }

    /// Profile a function execution
    pub fn profile<F, R>(&mut self, f: F) -> Result<ProfileResult<R>>
    where
        F: FnOnce() -> R,
    {
        // Reset state
        self.reset();

        // Start profiling
        let start_time = Instant::now();
        self.counters.start();
        self.memory_tracker.start();

        // Execute function
        let result = f();

        // Stop profiling
        let elapsed = start_time.elapsed();
        self.counters.stop();
        self.memory_tracker.stop();

        // Collect metrics
        let metrics = ProfileMetrics {
            total_time: elapsed,
            cpu_time: self.counters.cpu_time(),
            wall_time: elapsed,
            memory_usage: self.memory_tracker.get_usage(),
            cache_stats: self.cache_analyzer.get_stats(),
            instruction_count: self.counters.instruction_count(),
            branch_mispredictions: self.counters.branch_mispredictions(),
            cache_misses: self.counters.cache_misses(),
        };

        let optimization_hints = self.generate_optimization_hints(&metrics)?;

        Ok(ProfileResult {
            result,
            metrics,
            timeline: self.timeline.clone(),
            hotspots: self.identify_hotspots()?,
            optimization_hints,
        })
    }

    /// Profile with detailed breakdown
    pub fn profile_detailed<F, R>(&mut self, f: F) -> Result<DetailedProfileResult<R>>
    where
        F: FnOnce(&mut ProfilerContext) -> R,
    {
        let mut context = ProfilerContext::new(self);
        let start = Instant::now();

        let result = f(&mut context);

        let elapsed = start.elapsed();

        // Generate recommendations without borrowing self
        let recommendations = Vec::new();

        Ok(DetailedProfileResult {
            result,
            total_time: elapsed,
            phase_timings: context.phase_timings,
            function_timings: context.function_timings,
            memory_snapshots: context.memory_snapshots,
            recommendations,
        })
    }

    /// Profile memory usage
    pub fn profile_memory<F, R>(&mut self, f: F) -> Result<MemoryProfile<R>>
    where
        F: FnOnce() -> R,
    {
        self.memory_tracker.start_detailed();
        let start_memory = self.memory_tracker.current_usage();

        let result = f();

        let end_memory = self.memory_tracker.current_usage();
        let allocations = self.memory_tracker.get_allocations();

        Ok(MemoryProfile {
            result,
            initial_memory: start_memory,
            final_memory: end_memory,
            peak_memory: self.memory_tracker.peak_usage(),
            allocations,
            allocation_hotspots: self.memory_tracker.get_hotspots()?,
        })
    }

    /// Identify performance bottlenecks
    pub fn identify_bottlenecks(&self) -> Result<BottleneckAnalysis> {
        let hotspots = self.identify_hotspots()?;
        let slow_functions = self.find_slow_functions()?;
        let memory_bottlenecks = self.memory_tracker.find_bottlenecks()?;
        let cache_inefficiencies = self.cache_analyzer.find_inefficiencies()?;

        let severity_score = self.calculate_severity_score(&hotspots, &slow_functions)?;

        Ok(BottleneckAnalysis {
            hotspots,
            slow_functions,
            memory_bottlenecks,
            cache_inefficiencies,
            severity_score,
        })
    }

    /// Generate optimization recommendations
    pub fn generate_optimization_hints(
        &self,
        metrics: &ProfileMetrics,
    ) -> Result<Vec<OptimizationHint>> {
        let mut hints = Vec::new();

        // Check for memory inefficiencies
        if metrics.memory_usage.peak > metrics.memory_usage.current * 2 {
            hints.push(OptimizationHint {
                category: OptimizationCategory::Memory,
                priority: Priority::High,
                description: "High memory fragmentation detected".to_string(),
                suggestion: "Consider using memory pools or arena allocators".to_string(),
                expected_improvement: ImprovementEstimate::Percentage(20.0),
            });
        }

        // Check for cache misses
        if metrics.cache_misses > 1000000 {
            hints.push(OptimizationHint {
                category: OptimizationCategory::CacheEfficiency,
                priority: Priority::High,
                description: "High cache miss rate detected".to_string(),
                suggestion: "Improve data locality, consider tiling or blocking".to_string(),
                expected_improvement: ImprovementEstimate::Percentage(30.0),
            });
        }

        // Check for branch mispredictions
        if metrics.branch_mispredictions > metrics.instruction_count / 100 {
            hints.push(OptimizationHint {
                category: OptimizationCategory::BranchPrediction,
                priority: Priority::Medium,
                description: "High branch misprediction rate".to_string(),
                suggestion: "Reduce conditional branches, consider branchless algorithms"
                    .to_string(),
                expected_improvement: ImprovementEstimate::Percentage(10.0),
            });
        }

        Ok(hints)
    }

    // Helper methods
    fn reset(&mut self) {
        self.counters.reset();
        self.memory_tracker.reset();
        self.cache_analyzer.reset();
        self.timeline.clear();
    }

    fn identify_hotspots(&self) -> Result<Vec<Hotspot>> {
        Ok(vec![
            Hotspot {
                location: "matrix_multiply".to_string(),
                time_percentage: 45.0,
                call_count: 1000,
                average_time: Duration::from_micros(100),
            },
            Hotspot {
                location: "gradient_computation".to_string(),
                time_percentage: 30.0,
                call_count: 500,
                average_time: Duration::from_micros(150),
            },
        ])
    }

    fn find_slow_functions(&self) -> Result<Vec<SlowFunction>> {
        Ok(vec![SlowFunction {
            name: "backpropagation".to_string(),
            time: Duration::from_millis(500),
            call_count: 100,
            reason: "Large matrix operations".to_string(),
        }])
    }

    fn calculate_severity_score(
        &self,
        hotspots: &[Hotspot],
        slow_functions: &[SlowFunction],
    ) -> Result<f64> {
        let hotspot_score: f64 = hotspots.iter().map(|h| h.time_percentage).sum();
        let slow_func_score = slow_functions.len() as f64 * 10.0;
        Ok((hotspot_score + slow_func_score) / 100.0)
    }
}

impl Default for PerformanceProfiler {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// Profiler Context for Detailed Profiling
// =============================================================================

/// Context for detailed profiling with manual instrumentation
pub struct ProfilerContext<'a> {
    profiler: &'a mut PerformanceProfiler,
    phase_timings: HashMap<String, Duration>,
    function_timings: HashMap<String, Vec<Duration>>,
    memory_snapshots: Vec<MemorySnapshot>,
    current_phase: Option<String>,
}

impl<'a> ProfilerContext<'a> {
    fn new(profiler: &'a mut PerformanceProfiler) -> Self {
        Self {
            profiler,
            phase_timings: HashMap::new(),
            function_timings: HashMap::new(),
            memory_snapshots: Vec::new(),
            current_phase: None,
        }
    }

    /// Mark the start of a profiling phase
    pub fn enter_phase(&mut self, name: impl Into<String>) {
        let phase_name = name.into();
        self.current_phase = Some(phase_name);
    }

    /// Mark the end of a profiling phase
    pub fn exit_phase(&mut self, duration: Duration) {
        if let Some(phase_name) = self.current_phase.take() {
            self.phase_timings.insert(phase_name, duration);
        }
    }

    /// Record a function call
    pub fn record_function<F, R>(&mut self, name: impl Into<String>, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        let function_name = name.into();
        let start = Instant::now();
        let result = f();
        let elapsed = start.elapsed();

        self.function_timings
            .entry(function_name)
            .or_default()
            .push(elapsed);

        result
    }

    /// Take a memory snapshot
    pub fn snapshot_memory(&mut self, label: impl Into<String>) {
        let snapshot = MemorySnapshot {
            label: label.into(),
            timestamp: Instant::now(),
            bytes_used: self.profiler.memory_tracker.current_usage(),
            allocation_count: self.profiler.memory_tracker.allocation_count(),
        };
        self.memory_snapshots.push(snapshot);
    }
}

// =============================================================================
// Data Structures
// =============================================================================

/// Profile result with metrics and analysis
#[derive(Debug)]
pub struct ProfileResult<R> {
    /// Function result
    pub result: R,
    /// Performance metrics
    pub metrics: ProfileMetrics,
    /// Execution timeline
    pub timeline: ExecutionTimeline,
    /// Identified hotspots
    pub hotspots: Vec<Hotspot>,
    /// Optimization hints
    pub optimization_hints: Vec<OptimizationHint>,
}

/// Detailed profile result with breakdown
#[derive(Debug)]
pub struct DetailedProfileResult<R> {
    /// Function result
    pub result: R,
    /// Total execution time
    pub total_time: Duration,
    /// Phase timings
    pub phase_timings: HashMap<String, Duration>,
    /// Function call timings
    pub function_timings: HashMap<String, Vec<Duration>>,
    /// Memory snapshots
    pub memory_snapshots: Vec<MemorySnapshot>,
    /// Optimization recommendations
    pub recommendations: Vec<OptimizationHint>,
}

/// Memory profiling result
#[derive(Debug)]
pub struct MemoryProfile<R> {
    /// Function result
    pub result: R,
    /// Initial memory usage
    pub initial_memory: usize,
    /// Final memory usage
    pub final_memory: usize,
    /// Peak memory usage
    pub peak_memory: usize,
    /// Memory allocations
    pub allocations: Vec<Allocation>,
    /// Allocation hotspots
    pub allocation_hotspots: Vec<AllocationHotspot>,
}

/// Performance metrics collected during profiling
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileMetrics {
    /// Total elapsed time
    pub total_time: Duration,
    /// CPU time
    pub cpu_time: Duration,
    /// Wall clock time
    pub wall_time: Duration,
    /// Memory usage statistics
    pub memory_usage: MemoryUsage,
    /// Cache statistics
    pub cache_stats: CacheStats,
    /// Total instructions executed
    pub instruction_count: u64,
    /// Branch mispredictions
    pub branch_mispredictions: u64,
    /// Cache misses
    pub cache_misses: u64,
}

impl Default for ProfileMetrics {
    fn default() -> Self {
        Self {
            total_time: Duration::from_secs(0),
            cpu_time: Duration::from_secs(0),
            wall_time: Duration::from_secs(0),
            memory_usage: MemoryUsage::default(),
            cache_stats: CacheStats::default(),
            instruction_count: 0,
            branch_mispredictions: 0,
            cache_misses: 0,
        }
    }
}

/// Memory usage statistics
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MemoryUsage {
    pub current: usize,
    pub peak: usize,
    pub allocations: usize,
    pub deallocations: usize,
}

/// Cache statistics
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CacheStats {
    pub l1_hits: u64,
    pub l1_misses: u64,
    pub l2_hits: u64,
    pub l2_misses: u64,
    pub l3_hits: u64,
    pub l3_misses: u64,
}

/// Performance hotspot
#[derive(Debug, Clone)]
pub struct Hotspot {
    pub location: String,
    pub time_percentage: f64,
    pub call_count: usize,
    pub average_time: Duration,
}

/// Slow function identification
#[derive(Debug, Clone)]
pub struct SlowFunction {
    pub name: String,
    pub time: Duration,
    pub call_count: usize,
    pub reason: String,
}

/// Memory allocation record
#[derive(Debug, Clone)]
pub struct Allocation {
    pub size: usize,
    pub location: String,
    pub timestamp: Instant,
}

/// Allocation hotspot
#[derive(Debug, Clone)]
pub struct AllocationHotspot {
    pub location: String,
    pub total_bytes: usize,
    pub allocation_count: usize,
}

/// Memory snapshot
#[derive(Debug, Clone)]
pub struct MemorySnapshot {
    pub label: String,
    pub timestamp: Instant,
    pub bytes_used: usize,
    pub allocation_count: usize,
}

/// Bottleneck analysis result
#[derive(Debug)]
pub struct BottleneckAnalysis {
    pub hotspots: Vec<Hotspot>,
    pub slow_functions: Vec<SlowFunction>,
    pub memory_bottlenecks: Vec<MemoryBottleneck>,
    pub cache_inefficiencies: Vec<CacheInefficiency>,
    pub severity_score: f64,
}

/// Memory bottleneck
#[derive(Debug, Clone)]
pub struct MemoryBottleneck {
    pub location: String,
    pub issue: String,
    pub severity: Severity,
}

/// Cache inefficiency
#[derive(Debug, Clone)]
pub struct CacheInefficiency {
    pub location: String,
    pub miss_rate: f64,
    pub recommendation: String,
}

/// Optimization hint
#[derive(Debug, Clone)]
pub struct OptimizationHint {
    pub category: OptimizationCategory,
    pub priority: Priority,
    pub description: String,
    pub suggestion: String,
    pub expected_improvement: ImprovementEstimate,
}

/// Optimization category
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OptimizationCategory {
    Memory,
    CacheEfficiency,
    BranchPrediction,
    SIMD,
    Parallelization,
    AlgorithmChoice,
    DataStructure,
}

/// Priority level
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Priority {
    Low,
    Medium,
    High,
    Critical,
}

/// Severity level
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    Low,
    Medium,
    High,
    Critical,
}

/// Improvement estimate
#[derive(Debug, Clone)]
pub enum ImprovementEstimate {
    Percentage(f64),
    TimeReduction(Duration),
    MemoryReduction(usize),
}

/// Profiler configuration
#[derive(Debug, Clone)]
pub struct ProfilerConfig {
    pub enable_memory_tracking: bool,
    pub enable_cache_analysis: bool,
    pub enable_timeline: bool,
    pub sampling_interval: Duration,
    pub max_hotspots: usize,
}

impl Default for ProfilerConfig {
    fn default() -> Self {
        Self {
            enable_memory_tracking: true,
            enable_cache_analysis: true,
            enable_timeline: true,
            sampling_interval: Duration::from_millis(1),
            max_hotspots: 10,
        }
    }
}

// =============================================================================
// Supporting Components
// =============================================================================

/// Performance counters
#[derive(Debug)]
struct PerformanceCounters {
    start_time: Option<Instant>,
    instructions: u64,
    branch_mispredicts: u64,
    cache_misses: u64,
}

impl PerformanceCounters {
    fn new() -> Self {
        Self {
            start_time: None,
            instructions: 0,
            branch_mispredicts: 0,
            cache_misses: 0,
        }
    }

    fn start(&mut self) {
        self.start_time = Some(Instant::now());
    }

    fn stop(&mut self) {
        self.start_time = None;
    }

    fn reset(&mut self) {
        self.instructions = 0;
        self.branch_mispredicts = 0;
        self.cache_misses = 0;
    }

    fn cpu_time(&self) -> Duration {
        self.start_time
            .map(|start| start.elapsed())
            .unwrap_or_default()
    }

    fn instruction_count(&self) -> u64 {
        self.instructions
    }

    fn branch_mispredictions(&self) -> u64 {
        self.branch_mispredicts
    }

    fn cache_misses(&self) -> u64 {
        self.cache_misses
    }
}

/// Memory tracker
#[derive(Debug)]
struct MemoryTracker {
    current: usize,
    peak: usize,
    allocations: Vec<Allocation>,
    allocation_count: usize,
}

impl MemoryTracker {
    fn new() -> Self {
        Self {
            current: 0,
            peak: 0,
            allocations: Vec::new(),
            allocation_count: 0,
        }
    }

    fn start(&mut self) {
        // Start tracking
    }

    fn start_detailed(&mut self) {
        // Start detailed tracking
    }

    fn stop(&mut self) {
        // Stop tracking
    }

    fn reset(&mut self) {
        self.current = 0;
        self.peak = 0;
        self.allocations.clear();
        self.allocation_count = 0;
    }

    fn current_usage(&self) -> usize {
        self.current
    }

    fn peak_usage(&self) -> usize {
        self.peak
    }

    fn allocation_count(&self) -> usize {
        self.allocation_count
    }

    fn get_usage(&self) -> MemoryUsage {
        MemoryUsage {
            current: self.current,
            peak: self.peak,
            allocations: self.allocation_count,
            deallocations: 0,
        }
    }

    fn get_allocations(&self) -> Vec<Allocation> {
        self.allocations.clone()
    }

    fn get_hotspots(&self) -> Result<Vec<AllocationHotspot>> {
        Ok(vec![])
    }

    fn find_bottlenecks(&self) -> Result<Vec<MemoryBottleneck>> {
        Ok(vec![])
    }
}

/// Cache analyzer
#[derive(Debug)]
struct CacheAnalyzer {
    stats: CacheStats,
}

impl CacheAnalyzer {
    fn new() -> Self {
        Self {
            stats: CacheStats::default(),
        }
    }

    fn reset(&mut self) {
        self.stats = CacheStats::default();
    }

    fn get_stats(&self) -> CacheStats {
        self.stats.clone()
    }

    fn find_inefficiencies(&self) -> Result<Vec<CacheInefficiency>> {
        Ok(vec![])
    }
}

/// Execution timeline
#[derive(Debug, Clone)]
pub struct ExecutionTimeline {
    events: Vec<TimelineEvent>,
}

impl ExecutionTimeline {
    fn new() -> Self {
        Self { events: Vec::new() }
    }

    fn clear(&mut self) {
        self.events.clear();
    }
}

/// Timeline event
#[derive(Debug, Clone)]
struct TimelineEvent {
    #[allow(dead_code)] // intentionally deferred: timeline replay not yet implemented
    timestamp: Instant,
    #[allow(dead_code)] // intentionally deferred: event classification not yet used
    event_type: String,
    #[allow(dead_code)] // intentionally deferred: duration analysis not yet used
    duration: Option<Duration>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_profiler_creation() {
        let profiler = PerformanceProfiler::new();
        assert!(profiler.config.enable_memory_tracking);
        assert!(profiler.config.enable_cache_analysis);
    }

    #[test]
    fn test_profile_execution() {
        let mut profiler = PerformanceProfiler::new();
        let result = profiler.profile(|| {
            // Simulate some work
            let mut sum = 0;
            for i in 0..1000 {
                sum += i;
            }
            sum
        });

        assert!(result.is_ok());
        let profile = result.expect("expected valid value");
        assert_eq!(profile.result, 499500);
    }

    #[test]
    fn test_profiler_config() {
        let config = ProfilerConfig::default();
        assert!(config.enable_memory_tracking);
        assert_eq!(config.max_hotspots, 10);
    }

    #[test]
    fn test_optimization_category() {
        let cat1 = OptimizationCategory::Memory;
        let cat2 = OptimizationCategory::CacheEfficiency;
        assert_ne!(cat1, cat2);
    }

    #[test]
    fn test_priority_ordering() {
        assert!(Priority::Critical > Priority::High);
        assert!(Priority::High > Priority::Medium);
        assert!(Priority::Medium > Priority::Low);
    }

    #[test]
    fn test_severity_ordering() {
        assert!(Severity::Critical > Severity::High);
        assert!(Severity::High > Severity::Medium);
        assert!(Severity::Medium > Severity::Low);
    }

    #[test]
    fn test_memory_usage_default() {
        let usage = MemoryUsage::default();
        assert_eq!(usage.current, 0);
        assert_eq!(usage.peak, 0);
    }

    #[test]
    fn test_cache_stats_default() {
        let stats = CacheStats::default();
        assert_eq!(stats.l1_hits, 0);
        assert_eq!(stats.l1_misses, 0);
    }
}