// rust/01-performance-measurement.rs/*Performance measurement and profiling patterns for Rust*/usestd::time::{Duration,Instant};usestd::collections::HashMap;usestd::sync::Arc;usestd::thread;userayon::prelude::*;/// A high-performance data processor for benchmarking.pubstructDataProcessor{data:Vec<u64>,cache:HashMap<u64,u64>,}implDataProcessor{pubfnnew(size:usize)->Self{Self{data:(0..sizeasu64).collect(),cache:HashMap::new(),}}/// Process data with caching for performance measurement.pubfnprocess_with_cache(&mutself)->u64{letmutsum=0u64;for&valuein&self.data{ifletSome(&cached)=self.cache.get(&value){sum+=cached;}else{letprocessed=self.expensive_calculation(value);self.cache.insert(value,processed);sum+=processed;}}sum}/// Process data without caching for comparison.pubfnprocess_without_cache(&self)->u64{letmutsum=0u64;for&valuein&self.data{sum+=self.expensive_calculation(value);}sum}/// Process data in parallel for performance measurement.pubfnprocess_parallel(&self)->u64{self.data.par_iter().map(|&value|self.expensive_calculation(value)).sum()}/// Expensive calculation for benchmarking.fnexpensive_calculation(&self,value:u64)->u64{// Simulate expensive computationletmutresult=value;for_in0..1000{result=result.wrapping_mul(3).wrapping_add(1);}result}}/// Performance measurement utilities.pubstructPerformanceProfiler{measurements:Vec<(String,Duration)>,}implPerformanceProfiler{pubfnnew()->Self{Self{measurements:Vec::new(),}}/// Measure the execution time of a function.pubfnmeasure<F,R>(&mutself,name:&str,f:F)->RwhereF:FnOnce()->R,{letstart=Instant::now();letresult=f();letduration=start.elapsed();self.measurements.push((name.to_string(),duration));result}/// Get all measurements.pubfnget_measurements(&self)->&[(String,Duration)]{&self.measurements}/// Get the fastest measurement.pubfnget_fastest(&self)->Option<&(String,Duration)>{self.measurements.iter().min_by_key(|(_,duration)|*duration)}/// Get the slowest measurement.pubfnget_slowest(&self)->Option<&(String,Duration)>{self.measurements.iter().max_by_key(|(_,duration)|*duration)}/// Calculate performance improvement.pubfncalculate_improvement(&self,baseline:&str,optimized:&str)->Option<f64>{letbaseline_duration=self.measurements.iter().find(|(name,_)|name==baseline).map(|(_,duration)|duration.as_nanos())?;letoptimized_duration=self.measurements.iter().find(|(name,_)|name==optimized).map(|(_,duration)|duration.as_nanos())?;Some(baseline_durationasf64/optimized_durationasf64)}}/// Benchmark suite for performance testing.pubstructBenchmarkSuite{profiler:PerformanceProfiler,}implBenchmarkSuite{pubfnnew()->Self{Self{profiler:PerformanceProfiler::new(),}}/// Run comprehensive benchmarks.pubfnrun_benchmarks(&mutself,data_size:usize){letmutprocessor=DataProcessor::new(data_size);// Benchmark without cachingself.profiler.measure("without_cache",||{processor.process_without_cache()});// Benchmark with cachingself.profiler.measure("with_cache",||{processor.process_with_cache()});// Benchmark parallel processingself.profiler.measure("parallel",||{processor.process_parallel()});// Benchmark with different data sizesforsizein[100,1000,10000]{letmutsmall_processor=DataProcessor::new(size);self.profiler.measure(&format!("cached_{}",size),||{small_processor.process_with_cache()});}}/// Print benchmark results.pubfnprint_results(&self){println!("Benchmark Results:");println!("==================");for(name,duration)inself.profiler.get_measurements(){println!("{}: {:?}",name,duration);}ifletSome(fastest)=self.profiler.get_fastest(){println!("\nFastest: {} ({:?})",fastest.0,fastest.1);}ifletSome(slowest)=self.profiler.get_slowest(){println!("Slowest: {} ({:?})",slowest.0,slowest.1);}ifletSome(improvement)=self.profiler.calculate_improvement("without_cache","with_cache"){println!("Cache improvement: {:.2}x",improvement);}}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_performance_measurement(){letmutprofiler=PerformanceProfiler::new();letresult=profiler.measure("test",||{thread::sleep(Duration::from_millis(10));42});assert_eq!(result,42);assert_eq!(profiler.get_measurements().len(),1);}#[test]fntest_benchmark_suite(){letmutsuite=BenchmarkSuite::new();suite.run_benchmarks(1000);letmeasurements=suite.profiler.get_measurements();assert!(measurements.len()>=3);}}
// rust/02-memory-optimization.rs/*Memory optimization patterns for Rust applications*/usestd::collections::HashMap;usestd::alloc::{GlobalAlloc,Layout,System};usestd::sync::atomic::{AtomicUsize,Ordering};/// Custom memory allocator for tracking allocations.pubstructTrackingAllocator{inner:System,allocated:AtomicUsize,peak:AtomicUsize,}unsafeimplGlobalAllocforTrackingAllocator{unsafefnalloc(&self,layout:Layout)->*mutu8{letptr=self.inner.alloc(layout);if!ptr.is_null(){letsize=layout.size();letcurrent=self.allocated.fetch_add(size,Ordering::Relaxed);letpeak=self.peak.load(Ordering::Relaxed);ifcurrent+size>peak{self.peak.store(current+size,Ordering::Relaxed);}}ptr}unsafefndealloc(&self,ptr:*mutu8,layout:Layout){self.inner.dealloc(ptr,layout);self.allocated.fetch_sub(layout.size(),Ordering::Relaxed);}}implTrackingAllocator{pubfnnew()->Self{Self{inner:System,allocated:AtomicUsize::new(0),peak:AtomicUsize::new(0),}}pubfnget_allocated(&self)->usize{self.allocated.load(Ordering::Relaxed)}pubfnget_peak(&self)->usize{self.peak.load(Ordering::Relaxed)}}/// Memory-efficient data structure using object pooling.pubstructObjectPool<T>{objects:Vec<T>,available:Vec<usize>,next_id:usize,}impl<T:Default>ObjectPool<T>{pubfnnew(capacity:usize)->Self{letmutobjects=Vec::with_capacity(capacity);letmutavailable=Vec::with_capacity(capacity);foriin0..capacity{objects.push(T::default());available.push(i);}Self{objects,available,next_id:0,}}pubfnacquire(&mutself)->Option<usize>{self.available.pop()}pubfnrelease(&mutself,id:usize){ifid<self.objects.len(){self.available.push(id);}}pubfnget_mut(&mutself,id:usize)->Option<&mutT>{self.objects.get_mut(id)}pubfnget(&self,id:usize)->Option<&T>{self.objects.get(id)}}/// Memory-efficient string interning.pubstructStringInterner{strings:Vec<String>,indices:HashMap<String,usize>,}implStringInterner{pubfnnew()->Self{Self{strings:Vec::new(),indices:HashMap::new(),}}pubfnintern(&mutself,s:&str)->usize{ifletSome(&index)=self.indices.get(s){index}else{letindex=self.strings.len();self.strings.push(s.to_string());self.indices.insert(s.to_string(),index);index}}pubfnget(&self,index:usize)->Option<&str>{self.strings.get(index).map(|s|s.as_str())}pubfnlen(&self)->usize{self.strings.len()}}/// Memory-efficient data structure using small string optimization.#[derive(Clone)]pubstructSmallString{data:SmallStringData,}#[derive(Clone)]enumSmallStringData{Inline([u8;23]),// 23 bytes for inline storageHeap(String),}implSmallString{pubfnnew(s:&str)->Self{ifs.len()<=23{letmutbytes=[0u8;23];bytes[..s.len()].copy_from_slice(s.as_bytes());Self{data:SmallStringData::Inline(bytes),}}else{Self{data:SmallStringData::Heap(s.to_string()),}}}pubfnas_str(&self)->&str{match&self.data{SmallStringData::Inline(bytes)=>{letlen=bytes.iter().position(|&b|b==0).unwrap_or(bytes.len());unsafe{std::str::from_utf8_unchecked(&bytes[..len])}}SmallStringData::Heap(s)=>s.as_str(),}}pubfnlen(&self)->usize{match&self.data{SmallStringData::Inline(bytes)=>{bytes.iter().position(|&b|b==0).unwrap_or(bytes.len())}SmallStringData::Heap(s)=>s.len(),}}}/// Memory-efficient data structure using bit packing.pubstructBitPackedData{data:Vec<u64>,bits_per_item:usize,items_per_word:usize,}implBitPackedData{pubfnnew(bits_per_item:usize,capacity:usize)->Self{letitems_per_word=64/bits_per_item;letwords_needed=(capacity+items_per_word-1)/items_per_word;Self{data:vec![0;words_needed],bits_per_item,items_per_word,}}pubfnset(&mutself,index:usize,value:u64){letword_index=index/self.items_per_word;letitem_index=index%self.items_per_word;letbit_offset=item_index*self.bits_per_item;letmask=(1u64<<self.bits_per_item)-1;letshifted_value=value<<bit_offset;self.data[word_index]&=!(mask<<bit_offset);self.data[word_index]|=shifted_value;}pubfnget(&self,index:usize)->u64{letword_index=index/self.items_per_word;letitem_index=index%self.items_per_word;letbit_offset=item_index*self.bits_per_item;letmask=(1u64<<self.bits_per_item)-1;(self.data[word_index]>>bit_offset)&mask}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_object_pool(){letmutpool=ObjectPool::<String>::new(10);letid1=pool.acquire().unwrap();letid2=pool.acquire().unwrap();*pool.get_mut(id1).unwrap()="Hello".to_string();*pool.get_mut(id2).unwrap()="World".to_string();assert_eq!(pool.get(id1).unwrap(),"Hello");assert_eq!(pool.get(id2).unwrap(),"World");pool.release(id1);pool.release(id2);}#[test]fntest_string_interner(){letmutinterner=StringInterner::new();letid1=interner.intern("Hello");letid2=interner.intern("World");letid3=interner.intern("Hello");// Should return same IDassert_eq!(id1,id3);assert_ne!(id1,id2);assert_eq!(interner.get(id1),Some("Hello"));assert_eq!(interner.get(id2),Some("World"));}#[test]fntest_small_string(){lets1=SmallString::new("Hello");lets2=SmallString::new("This is a very long string that should be stored on the heap");assert_eq!(s1.as_str(),"Hello");assert_eq!(s1.len(),5);assert_eq!(s2.as_str(),"This is a very long string that should be stored on the heap");assert_eq!(s2.len(),58);}#[test]fntest_bit_packed_data(){letmutdata=BitPackedData::new(4,100);// 4 bits per itemdata.set(0,5);data.set(1,10);data.set(2,15);assert_eq!(data.get(0),5);assert_eq!(data.get(1),10);assert_eq!(data.get(2),15);}}
// 1. Performance measurementusestd::time::Instant;letstart=Instant::now();// Your code hereletduration=start.elapsed();// 2. Memory optimizationusestd::collections::HashMap;letmutcache=HashMap::new();// Use object pooling and string interning// 3. CPU optimizationusestd::simd::*;leta=f32x8::from_slice(&data);letb=f32x8::from_slice(&other_data);letresult=a*b;// 4. Cache optimization// Use SoA (Structure of Arrays) instead of AoS (Array of Structures)// 5. Branch prediction// Use branchless programming techniques