Skip to main content

torsh_profiler/
optimization.rs

1//! Performance optimizations and overhead minimization
2//!
3//! This module contains optimizations to minimize profiling overhead and improve
4//! data structure efficiency for high-performance profiling scenarios.
5
6use parking_lot::RwLock;
7use std::collections::HashMap;
8use std::mem;
9use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering};
10use std::sync::Arc;
11use std::time::Instant;
12
13/// Lock-free event buffer using ring buffer for minimal overhead
14pub struct LockFreeEventBuffer<T> {
15    buffer: Vec<AtomicOption<T>>,
16    capacity: usize,
17    head: AtomicUsize,
18    tail: AtomicUsize,
19    mask: usize,
20}
21
22/// Atomic option type for lock-free data structures
23struct AtomicOption<T> {
24    data: parking_lot::Mutex<Option<T>>,
25}
26
27impl<T> AtomicOption<T> {
28    fn new() -> Self {
29        Self {
30            data: parking_lot::Mutex::new(None),
31        }
32    }
33
34    fn take(&self) -> Option<T> {
35        self.data.lock().take()
36    }
37
38    fn store(&self, value: T) -> bool {
39        let mut data = self.data.lock();
40        if data.is_none() {
41            *data = Some(value);
42            true
43        } else {
44            false
45        }
46    }
47}
48
49impl<T> LockFreeEventBuffer<T> {
50    /// Create a new lock-free event buffer with given capacity (must be power of 2)
51    pub fn new(capacity: usize) -> Self {
52        assert!(capacity.is_power_of_two(), "Capacity must be power of 2");
53
54        let mut buffer = Vec::with_capacity(capacity);
55        for _ in 0..capacity {
56            buffer.push(AtomicOption::new());
57        }
58
59        Self {
60            buffer,
61            capacity,
62            head: AtomicUsize::new(0),
63            tail: AtomicUsize::new(0),
64            mask: capacity - 1,
65        }
66    }
67
68    /// Push an item to the buffer (returns false if buffer is full)
69    pub fn push(&self, item: T) -> bool {
70        let mut item = Some(item);
71        loop {
72            let tail = self.tail.load(Ordering::Acquire);
73            let next_tail = (tail + 1) & self.mask;
74            let head = self.head.load(Ordering::Acquire);
75
76            // Check if buffer is full
77            if next_tail == head {
78                return false;
79            }
80
81            // Check if the slot is available first before taking the item
82            if self.buffer[tail]
83                .data
84                .try_lock()
85                .is_some_and(|guard| guard.is_none())
86            {
87                if let Some(value) = item.take() {
88                    if self.buffer[tail].store(value) {
89                        // Update tail pointer
90                        if self
91                            .tail
92                            .compare_exchange_weak(
93                                tail,
94                                next_tail,
95                                Ordering::Release,
96                                Ordering::Relaxed,
97                            )
98                            .is_ok()
99                        {
100                            return true;
101                        }
102                        // If compare_exchange failed, retrieve item for next iteration
103                        item = self.buffer[tail].take();
104                    }
105                    // Note: if store fails here, it means another thread filled the slot
106                    // between our check and store - we've lost the item but that's acceptable
107                    // in a lock-free structure as it's a rare race condition
108                }
109            }
110        }
111    }
112
113    /// Pop an item from the buffer (returns None if buffer is empty)
114    pub fn pop(&self) -> Option<T> {
115        loop {
116            let head = self.head.load(Ordering::Acquire);
117            let tail = self.tail.load(Ordering::Acquire);
118
119            // Check if buffer is empty
120            if head == tail {
121                return None;
122            }
123
124            // Try to take the item
125            if let Some(item) = self.buffer[head].take() {
126                let next_head = (head + 1) & self.mask;
127                // Update head pointer
128                if self
129                    .head
130                    .compare_exchange_weak(head, next_head, Ordering::Release, Ordering::Relaxed)
131                    .is_ok()
132                {
133                    return Some(item);
134                }
135            }
136        }
137    }
138
139    /// Get current buffer usage
140    pub fn len(&self) -> usize {
141        let tail = self.tail.load(Ordering::Acquire);
142        let head = self.head.load(Ordering::Acquire);
143        (tail.wrapping_sub(head)) & self.mask
144    }
145
146    /// Check if buffer is empty
147    pub fn is_empty(&self) -> bool {
148        self.head.load(Ordering::Acquire) == self.tail.load(Ordering::Acquire)
149    }
150
151    /// Get buffer capacity
152    pub fn capacity(&self) -> usize {
153        self.capacity
154    }
155}
156
157// Thread-local profiling data to minimize contention
158thread_local! {
159    static THREAD_LOCAL_BUFFER: std::cell::RefCell<ThreadLocalProfileData> =
160        std::cell::RefCell::new(ThreadLocalProfileData::new());
161}
162
163/// Thread-local profiling data structure
164pub struct ThreadLocalProfileData {
165    events: Vec<crate::ProfileEvent>,
166    memory_events: Vec<crate::memory::MemoryEvent>,
167    call_stack_depth: usize,
168    total_overhead_ns: u64,
169    event_count: usize,
170    max_buffer_size: usize,
171}
172
173impl ThreadLocalProfileData {
174    fn new() -> Self {
175        Self {
176            events: Vec::with_capacity(1024), // Pre-allocate to avoid reallocations
177            memory_events: Vec::with_capacity(512),
178            call_stack_depth: 0,
179            total_overhead_ns: 0,
180            event_count: 0,
181            max_buffer_size: 4096,
182        }
183    }
184
185    /// Add a profiling event with minimal overhead
186    pub fn add_event(&mut self, event: crate::ProfileEvent) {
187        if self.events.len() < self.max_buffer_size {
188            self.events.push(event);
189            self.event_count += 1;
190        } else {
191            // Buffer full, replace oldest event (ring buffer behavior)
192            let index = self.event_count % self.max_buffer_size;
193            self.events[index] = event;
194            self.event_count += 1;
195        }
196    }
197
198    /// Drain events and return them
199    pub fn drain_events(&mut self) -> Vec<crate::ProfileEvent> {
200        mem::take(&mut self.events)
201    }
202
203    /// Get current buffer usage statistics
204    pub fn get_stats(&self) -> ThreadLocalStats {
205        ThreadLocalStats {
206            event_count: self.event_count,
207            buffer_size: self.events.len(),
208            call_stack_depth: self.call_stack_depth,
209            total_overhead_ns: self.total_overhead_ns,
210            capacity_utilization: self.events.len() as f64 / self.max_buffer_size as f64,
211        }
212    }
213}
214
215/// Statistics for thread-local profiling data
216#[derive(Debug, Clone)]
217pub struct ThreadLocalStats {
218    pub event_count: usize,
219    pub buffer_size: usize,
220    pub call_stack_depth: usize,
221    pub total_overhead_ns: u64,
222    pub capacity_utilization: f64,
223}
224
225/// Optimized profiler with minimal overhead
226pub struct OptimizedProfiler {
227    enabled: AtomicBool,
228    global_buffer: LockFreeEventBuffer<crate::ProfileEvent>,
229    collection_thread: Option<std::thread::JoinHandle<()>>,
230    stop_signal: Arc<AtomicBool>,
231    overhead_tracker: OverheadTracker,
232    sampling_config: SamplingConfig,
233}
234
235/// Overhead tracking for performance analysis
236pub struct OverheadTracker {
237    total_calls: AtomicU64,
238    total_overhead_ns: AtomicU64,
239    max_overhead_ns: AtomicU64,
240    histogram: RwLock<[u64; 20]>, // Histogram buckets for overhead distribution
241}
242
243impl OverheadTracker {
244    fn new() -> Self {
245        Self {
246            total_calls: AtomicU64::new(0),
247            total_overhead_ns: AtomicU64::new(0),
248            max_overhead_ns: AtomicU64::new(0),
249            histogram: RwLock::new([0; 20]),
250        }
251    }
252
253    /// Record overhead measurement
254    pub fn record_overhead(&self, overhead_ns: u64) {
255        self.total_calls.fetch_add(1, Ordering::Relaxed);
256        self.total_overhead_ns
257            .fetch_add(overhead_ns, Ordering::Relaxed);
258
259        // Update maximum overhead
260        let mut current_max = self.max_overhead_ns.load(Ordering::Relaxed);
261        while overhead_ns > current_max {
262            match self.max_overhead_ns.compare_exchange_weak(
263                current_max,
264                overhead_ns,
265                Ordering::Relaxed,
266                Ordering::Relaxed,
267            ) {
268                Ok(_) => break,
269                Err(actual) => current_max = actual,
270            }
271        }
272
273        // Update histogram
274        let bucket = ((overhead_ns as f64).log2().max(0.0) as usize).min(19);
275        if let Some(mut histogram) = self.histogram.try_write() {
276            histogram[bucket] += 1;
277        }
278    }
279
280    /// Get overhead statistics
281    pub fn get_stats(&self) -> DetailedOverheadStats {
282        let total_calls = self.total_calls.load(Ordering::Relaxed);
283        let total_overhead = self.total_overhead_ns.load(Ordering::Relaxed);
284        let avg_overhead = if total_calls > 0 {
285            total_overhead as f64 / total_calls as f64
286        } else {
287            0.0
288        };
289
290        DetailedOverheadStats {
291            total_calls,
292            total_overhead_ns: total_overhead,
293            avg_overhead_ns: avg_overhead,
294            max_overhead_ns: self.max_overhead_ns.load(Ordering::Relaxed),
295            histogram: *self.histogram.read(),
296        }
297    }
298}
299
300/// Detailed overhead statistics
301#[derive(Debug, Clone)]
302pub struct DetailedOverheadStats {
303    pub total_calls: u64,
304    pub total_overhead_ns: u64,
305    pub avg_overhead_ns: f64,
306    pub max_overhead_ns: u64,
307    pub histogram: [u64; 20],
308}
309
310/// Sampling configuration for reduced overhead
311#[derive(Debug, Clone)]
312pub struct SamplingConfig {
313    /// Sample every N events (1 = no sampling, 100 = sample 1 in 100)
314    pub sample_rate: usize,
315    /// Adaptive sampling based on overhead
316    pub adaptive_sampling: bool,
317    /// Maximum allowed overhead percentage (0.0 to 1.0)
318    pub max_overhead_percent: f64,
319    /// Minimum sampling rate (always sample at least this rate)
320    pub min_sample_rate: usize,
321}
322
323impl Default for SamplingConfig {
324    fn default() -> Self {
325        Self {
326            sample_rate: 1,
327            adaptive_sampling: false,
328            max_overhead_percent: 0.05, // 5% overhead maximum
329            min_sample_rate: 1000,      // Sample at least 1 in 1000
330        }
331    }
332}
333
334impl Default for OptimizedProfiler {
335    fn default() -> Self {
336        Self::new()
337    }
338}
339
340impl OptimizedProfiler {
341    /// Create a new optimized profiler
342    pub fn new() -> Self {
343        let stop_signal = Arc::new(AtomicBool::new(false));
344        let global_buffer = LockFreeEventBuffer::new(8192); // 8K events
345
346        Self {
347            enabled: AtomicBool::new(true),
348            global_buffer,
349            collection_thread: None,
350            stop_signal,
351            overhead_tracker: OverheadTracker::new(),
352            sampling_config: SamplingConfig::default(),
353        }
354    }
355
356    /// Start the background collection thread
357    pub fn start_collection_thread(&mut self) {
358        if self.collection_thread.is_some() {
359            return; // Already started
360        }
361
362        let stop_signal = self.stop_signal.clone();
363        let handle = std::thread::spawn(move || {
364            Self::collection_thread_main(stop_signal);
365        });
366
367        self.collection_thread = Some(handle);
368    }
369
370    /// Stop the background collection thread
371    pub fn stop_collection_thread(&mut self) {
372        if let Some(handle) = self.collection_thread.take() {
373            self.stop_signal.store(true, Ordering::Release);
374            let _ = handle.join();
375            self.stop_signal.store(false, Ordering::Release);
376        }
377    }
378
379    /// Record an event with minimal overhead
380    pub fn record_event_fast(&self, event: crate::ProfileEvent) {
381        if !self.enabled.load(Ordering::Relaxed) {
382            return;
383        }
384
385        let start_time = Instant::now();
386
387        // Try thread-local first for minimal contention
388        THREAD_LOCAL_BUFFER.with(|buffer| {
389            let mut buffer = buffer.borrow_mut();
390            buffer.add_event(event);
391        });
392
393        let overhead = start_time.elapsed().as_nanos() as u64;
394        self.overhead_tracker.record_overhead(overhead);
395    }
396
397    /// Flush thread-local buffers to global buffer
398    pub fn flush_thread_local(&self) {
399        THREAD_LOCAL_BUFFER.with(|buffer| {
400            let mut buffer = buffer.borrow_mut();
401            let events = buffer.drain_events();
402
403            for event in events {
404                if !self.global_buffer.push(event) {
405                    // Buffer full, event dropped
406                    break;
407                }
408            }
409        });
410    }
411
412    /// Get profiler statistics
413    pub fn get_stats(&self) -> ProfilerStats {
414        let overhead_stats = self.overhead_tracker.get_stats();
415        let buffer_usage = self.global_buffer.len() as f64 / self.global_buffer.capacity() as f64;
416
417        let thread_local_stats = THREAD_LOCAL_BUFFER.with(|buffer| buffer.borrow().get_stats());
418
419        ProfilerStats {
420            enabled: self.enabled.load(Ordering::Relaxed),
421            overhead_stats,
422            buffer_usage,
423            thread_local_stats,
424            sampling_config: self.sampling_config.clone(),
425        }
426    }
427
428    /// Optimize sampling rate based on overhead
429    pub fn optimize_sampling(&mut self) {
430        if !self.sampling_config.adaptive_sampling {
431            return;
432        }
433
434        let stats = self.overhead_tracker.get_stats();
435        if stats.total_calls < 1000 {
436            return; // Not enough data
437        }
438
439        let overhead_percent = stats.avg_overhead_ns / 1_000_000_000.0; // Convert to seconds
440
441        if overhead_percent > self.sampling_config.max_overhead_percent {
442            // Increase sampling rate (sample less frequently)
443            self.sampling_config.sample_rate =
444                (self.sampling_config.sample_rate * 2).min(self.sampling_config.min_sample_rate);
445        } else if overhead_percent < self.sampling_config.max_overhead_percent * 0.5 {
446            // Decrease sampling rate (sample more frequently)
447            self.sampling_config.sample_rate = (self.sampling_config.sample_rate / 2).max(1);
448        }
449    }
450
451    /// Collection thread main loop
452    fn collection_thread_main(stop_signal: Arc<AtomicBool>) {
453        let mut flush_interval = std::time::Duration::from_millis(100);
454
455        while !stop_signal.load(Ordering::Acquire) {
456            std::thread::sleep(flush_interval);
457
458            // Global collection logic would go here
459            // For now, just a placeholder that adjusts flush interval based on load
460
461            // Adaptive flush interval based on system load
462            let load = 1.0; // Fallback - sys_info crate not available
463            if load > 2.0 {
464                flush_interval = std::time::Duration::from_millis(200); // Slower when system is busy
465            } else {
466                flush_interval = std::time::Duration::from_millis(50); // Faster when system is idle
467            }
468        }
469    }
470}
471
472/// Comprehensive profiler statistics
473#[derive(Debug, Clone)]
474pub struct ProfilerStats {
475    pub enabled: bool,
476    pub overhead_stats: DetailedOverheadStats,
477    pub buffer_usage: f64,
478    pub thread_local_stats: ThreadLocalStats,
479    pub sampling_config: SamplingConfig,
480}
481
482/// Memory pool for efficient event allocation
483pub struct EventMemoryPool {
484    #[allow(clippy::vec_box)]
485    pool: parking_lot::Mutex<Vec<Box<crate::ProfileEvent>>>,
486    max_pool_size: usize,
487    allocations: AtomicU64,
488    deallocations: AtomicU64,
489}
490
491impl EventMemoryPool {
492    /// Create a new memory pool
493    pub fn new(max_pool_size: usize) -> Self {
494        Self {
495            pool: parking_lot::Mutex::new(Vec::with_capacity(max_pool_size)),
496            max_pool_size,
497            allocations: AtomicU64::new(0),
498            deallocations: AtomicU64::new(0),
499        }
500    }
501
502    /// Allocate an event from the pool or create new
503    pub fn allocate(&self) -> Box<crate::ProfileEvent> {
504        self.allocations.fetch_add(1, Ordering::Relaxed);
505
506        if let Some(mut pool) = self.pool.try_lock() {
507            if let Some(event) = pool.pop() {
508                return event;
509            }
510        }
511
512        // Pool empty or locked, allocate new
513        Box::new(crate::ProfileEvent {
514            name: String::new(),
515            category: String::new(),
516            start_us: 0,
517            duration_us: 0,
518            thread_id: 0,
519            operation_count: None,
520            flops: None,
521            bytes_transferred: None,
522            stack_trace: None,
523        })
524    }
525
526    /// Return an event to the pool
527    pub fn deallocate(&self, mut event: Box<crate::ProfileEvent>) {
528        self.deallocations.fetch_add(1, Ordering::Relaxed);
529
530        // Clear the event data
531        event.name.clear();
532        event.category.clear();
533        event.start_us = 0;
534        event.duration_us = 0;
535        event.thread_id = 0;
536        event.operation_count = None;
537        event.flops = None;
538        event.bytes_transferred = None;
539        event.stack_trace = None;
540
541        if let Some(mut pool) = self.pool.try_lock() {
542            if pool.len() < self.max_pool_size {
543                pool.push(event);
544            }
545        }
546    }
547
548    /// Get pool statistics
549    pub fn get_stats(&self) -> PoolStats {
550        let pool_size = self.pool.lock().len();
551        PoolStats {
552            pool_size,
553            max_pool_size: self.max_pool_size,
554            allocations: self.allocations.load(Ordering::Relaxed),
555            deallocations: self.deallocations.load(Ordering::Relaxed),
556        }
557    }
558}
559
560/// Memory pool statistics
561#[derive(Debug, Clone)]
562pub struct PoolStats {
563    pub pool_size: usize,
564    pub max_pool_size: usize,
565    pub allocations: u64,
566    pub deallocations: u64,
567}
568
569/// Compact event representation for minimal memory usage
570#[repr(C)]
571#[derive(Debug, Clone, Copy)]
572pub struct CompactEvent {
573    /// Packed timing information (start time and duration)
574    pub timing: u64,
575    /// Thread ID and category ID packed together
576    pub thread_category: u32,
577    /// Name ID (index into string table)
578    pub name_id: u32,
579}
580
581impl CompactEvent {
582    /// Create a new compact event
583    pub fn new(
584        start_us: u32,
585        duration_us: u32,
586        thread_id: u16,
587        category_id: u8,
588        name_id: u32,
589    ) -> Self {
590        let timing = ((start_us as u64) << 32) | (duration_us as u64);
591        let thread_category = ((thread_id as u32) << 16) | (category_id as u32);
592
593        Self {
594            timing,
595            thread_category,
596            name_id,
597        }
598    }
599
600    /// Extract start time in microseconds
601    pub fn start_us(&self) -> u32 {
602        (self.timing >> 32) as u32
603    }
604
605    /// Extract duration in microseconds
606    pub fn duration_us(&self) -> u32 {
607        self.timing as u32
608    }
609
610    /// Extract thread ID
611    pub fn thread_id(&self) -> u16 {
612        (self.thread_category >> 16) as u16
613    }
614
615    /// Extract category ID
616    pub fn category_id(&self) -> u8 {
617        self.thread_category as u8
618    }
619}
620
621/// String interning for efficient string storage
622pub struct StringInterner {
623    strings: RwLock<Vec<String>>,
624    string_to_id: RwLock<HashMap<String, u32>>,
625    next_id: AtomicU32,
626}
627
628impl Default for StringInterner {
629    fn default() -> Self {
630        Self::new()
631    }
632}
633
634impl StringInterner {
635    /// Create a new string interner
636    pub fn new() -> Self {
637        Self {
638            strings: RwLock::new(Vec::new()),
639            string_to_id: RwLock::new(HashMap::new()),
640            next_id: AtomicU32::new(0),
641        }
642    }
643
644    /// Intern a string and return its ID
645    pub fn intern(&self, s: &str) -> u32 {
646        // Fast path: check if already interned
647        if let Some(map) = self.string_to_id.try_read() {
648            if let Some(&id) = map.get(s) {
649                return id;
650            }
651        }
652
653        // Slow path: add new string
654        let mut strings = self.strings.write();
655        let mut map = self.string_to_id.write();
656
657        // Double-check in case another thread added it
658        if let Some(&id) = map.get(s) {
659            return id;
660        }
661
662        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
663        strings.push(s.to_string());
664        map.insert(s.to_string(), id);
665        id
666    }
667
668    /// Get string by ID
669    pub fn get_string(&self, id: u32) -> Option<String> {
670        self.strings.read().get(id as usize).cloned()
671    }
672
673    /// Get statistics
674    pub fn get_stats(&self) -> InternerStats {
675        let strings = self.strings.read();
676        let total_size = strings.iter().map(|s| s.len()).sum();
677
678        InternerStats {
679            string_count: strings.len(),
680            total_size,
681            next_id: self.next_id.load(Ordering::Relaxed),
682        }
683    }
684}
685
686/// String interner statistics
687#[derive(Debug, Clone)]
688pub struct InternerStats {
689    pub string_count: usize,
690    pub total_size: usize,
691    pub next_id: u32,
692}
693
694/// Global optimized profiler instance
695static mut OPTIMIZED_PROFILER: Option<OptimizedProfiler> = None;
696static PROFILER_INIT: std::sync::Once = std::sync::Once::new();
697
698/// Get or create the global optimized profiler
699pub fn get_optimized_profiler() -> &'static mut OptimizedProfiler {
700    unsafe {
701        PROFILER_INIT.call_once(|| {
702            OPTIMIZED_PROFILER = Some(OptimizedProfiler::new());
703        });
704        OPTIMIZED_PROFILER
705            .as_mut()
706            .expect("OPTIMIZED_PROFILER should be initialized by call_once")
707    }
708}
709
710/// Initialize optimized profiling
711pub fn init_optimized_profiling() {
712    let profiler = get_optimized_profiler();
713    profiler.start_collection_thread();
714}
715
716/// Record an event with optimized path
717pub fn record_event_optimized(event: crate::ProfileEvent) {
718    let profiler = get_optimized_profiler();
719    profiler.record_event_fast(event);
720}
721
722/// Flush all buffers
723pub fn flush_optimized_buffers() {
724    let profiler = get_optimized_profiler();
725    profiler.flush_thread_local();
726}
727
728/// Get optimization statistics
729pub fn get_optimization_stats() -> ProfilerStats {
730    let profiler = get_optimized_profiler();
731    profiler.get_stats()
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737    use std::time::Duration;
738
739    #[test]
740    fn test_lock_free_buffer() {
741        let buffer = LockFreeEventBuffer::new(16);
742
743        // Test push/pop
744        assert!(buffer.push("item1"));
745        assert!(buffer.push("item2"));
746        assert_eq!(buffer.len(), 2);
747
748        assert_eq!(buffer.pop(), Some("item1"));
749        assert_eq!(buffer.pop(), Some("item2"));
750        assert_eq!(buffer.pop(), None);
751        assert!(buffer.is_empty());
752    }
753
754    #[test]
755    fn test_overhead_tracker() {
756        let tracker = OverheadTracker::new();
757
758        tracker.record_overhead(1000);
759        tracker.record_overhead(2000);
760        tracker.record_overhead(1500);
761
762        let stats = tracker.get_stats();
763        assert_eq!(stats.total_calls, 3);
764        assert_eq!(stats.total_overhead_ns, 4500);
765        assert_eq!(stats.avg_overhead_ns, 1500.0);
766        assert_eq!(stats.max_overhead_ns, 2000);
767    }
768
769    #[test]
770    fn test_event_memory_pool() {
771        let pool = EventMemoryPool::new(10);
772
773        // Allocate and deallocate
774        let event1 = pool.allocate();
775        let event2 = pool.allocate();
776
777        let stats = pool.get_stats();
778        assert_eq!(stats.allocations, 2);
779
780        pool.deallocate(event1);
781        pool.deallocate(event2);
782
783        let stats = pool.get_stats();
784        assert_eq!(stats.deallocations, 2);
785        assert_eq!(stats.pool_size, 2);
786    }
787
788    #[test]
789    fn test_compact_event() {
790        let event = CompactEvent::new(1000, 500, 123, 5, 42);
791
792        assert_eq!(event.start_us(), 1000);
793        assert_eq!(event.duration_us(), 500);
794        assert_eq!(event.thread_id(), 123);
795        assert_eq!(event.category_id(), 5);
796        assert_eq!(event.name_id, 42);
797    }
798
799    #[test]
800    fn test_string_interner() {
801        let interner = StringInterner::new();
802
803        let id1 = interner.intern("test_string");
804        let id2 = interner.intern("another_string");
805        let id3 = interner.intern("test_string"); // Should reuse ID
806
807        assert_eq!(id1, id3);
808        assert_ne!(id1, id2);
809
810        assert_eq!(interner.get_string(id1), Some("test_string".to_string()));
811        assert_eq!(interner.get_string(id2), Some("another_string".to_string()));
812
813        let stats = interner.get_stats();
814        assert_eq!(stats.string_count, 2);
815    }
816
817    #[test]
818    fn test_thread_local_buffer() {
819        let event = crate::ProfileEvent {
820            name: "test".to_string(),
821            category: "test".to_string(),
822            start_us: 0,
823            duration_us: 1000,
824            thread_id: 1,
825            operation_count: Some(1),
826            flops: None,
827            bytes_transferred: None,
828            stack_trace: None,
829        };
830
831        THREAD_LOCAL_BUFFER.with(|buffer| {
832            let mut buffer = buffer.borrow_mut();
833            buffer.add_event(event.clone());
834            buffer.add_event(event);
835
836            let stats = buffer.get_stats();
837            assert_eq!(stats.event_count, 2);
838            assert_eq!(stats.buffer_size, 2);
839        });
840    }
841
842    #[test]
843    fn test_optimized_profiler() {
844        let mut profiler = OptimizedProfiler::new();
845
846        let event = crate::ProfileEvent {
847            name: "test_event".to_string(),
848            category: "test".to_string(),
849            start_us: 0,
850            duration_us: 1000,
851            thread_id: 1,
852            operation_count: Some(1),
853            flops: None,
854            bytes_transferred: None,
855            stack_trace: None,
856        };
857
858        profiler.record_event_fast(event);
859
860        let stats = profiler.get_stats();
861        assert!(stats.enabled);
862        assert!(stats.overhead_stats.total_calls > 0);
863    }
864
865    #[test]
866    fn test_sampling_optimization() {
867        let mut profiler = OptimizedProfiler::new();
868        profiler.sampling_config.adaptive_sampling = true;
869        profiler.sampling_config.max_overhead_percent = 0.01; // 1%
870
871        // Simulate high overhead
872        for _ in 0..2000 {
873            profiler.overhead_tracker.record_overhead(1_000_000); // 1ms overhead
874        }
875
876        let old_rate = profiler.sampling_config.sample_rate;
877        profiler.optimize_sampling();
878
879        // Should increase sampling rate due to high overhead
880        assert!(profiler.sampling_config.sample_rate >= old_rate);
881    }
882}