1use crate::{MobileBackend, MobileConfig, MobilePlatform};
7use serde::{Deserialize, Serialize};
8use std::collections::{HashMap, VecDeque};
9use std::time::{Duration, Instant};
10use trustformers_core::error::{CoreError, Result};
11use trustformers_core::TrustformersError;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct AdvancedProfilerConfig {
16 pub enable_memory_tracking: bool,
18 pub enable_thermal_monitoring: bool,
20 pub enable_power_tracking: bool,
22 pub enable_operation_profiling: bool,
24 pub enable_real_time_viz: bool,
26 pub sampling_interval_ms: u64,
28 pub max_history_length: usize,
30 pub output_format: ProfilerOutputFormat,
32 pub enable_gpu_profiling: bool,
34 pub enable_network_tracking: bool,
36}
37
38impl Default for AdvancedProfilerConfig {
39 fn default() -> Self {
40 Self {
41 enable_memory_tracking: true,
42 enable_thermal_monitoring: true,
43 enable_power_tracking: true,
44 enable_operation_profiling: true,
45 enable_real_time_viz: false,
46 sampling_interval_ms: 100, max_history_length: 1000, output_format: ProfilerOutputFormat::Json,
49 enable_gpu_profiling: true,
50 enable_network_tracking: false,
51 }
52 }
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
57pub enum ProfilerOutputFormat {
58 Json,
59 Csv,
60 Flamegraph,
61 Chrome,
62 Custom(String),
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct PerformanceMetrics {
68 pub timestamp: u64,
70 pub cpu_usage: f32,
72 pub memory_usage: u64,
74 pub peak_memory: u64,
76 pub gpu_usage: Option<f32>,
78 pub gpu_memory: Option<u64>,
80 pub temperature: Option<f32>,
82 pub battery_level: Option<f32>,
84 pub power_consumption: Option<f32>,
86 pub network_sent_bytes: Option<u64>,
88 pub network_received_bytes: Option<u64>,
90 pub fps: Option<f32>,
92 pub inference_latency_ms: Option<f32>,
94 pub throughput_ips: Option<f32>,
96}
97
98#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct OperationProfile {
101 pub operation_name: String,
103 pub operation_type: OperationType,
105 pub execution_time_us: u64,
107 pub memory_allocated_bytes: u64,
109 pub memory_freed_bytes: u64,
111 pub flops: Option<u64>,
113 pub input_shapes: Vec<Vec<usize>>,
115 pub output_shape: Vec<usize>,
117 pub gpu_kernel_time_us: Option<u64>,
119 pub cache_hit_rate: Option<f32>,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
125pub enum OperationType {
126 Convolution,
127 LinearTransform,
128 Attention,
129 Normalization,
130 Activation,
131 Pooling,
132 Quantization,
133 Dequantization,
134 MemoryCopy,
135 DataTransfer,
136 Custom(String),
137}
138
139#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct ThermalAnalysis {
142 pub temperature_zones: HashMap<String, f32>,
144 pub is_throttling: bool,
146 pub temperature_trend: TemperatureTrend,
148 pub time_to_throttling_ms: Option<u64>,
150 pub recommended_action: ThermalRecommendation,
152}
153
154#[derive(Debug, Clone, Serialize, Deserialize)]
156pub enum TemperatureTrend {
157 Cooling,
158 Stable,
159 Rising,
160 Critical,
161}
162
163#[derive(Debug, Clone, Serialize, Deserialize)]
165pub enum ThermalRecommendation {
166 Continue,
167 ReduceFrequency,
168 PauseInference,
169 SwitchToLowerPrecision,
170 EnableThermalManagement,
171}
172
173#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct PowerAnalysis {
176 pub current_power_w: f32,
178 pub average_power_w: f32,
180 pub peak_power_w: f32,
182 pub battery_life_remaining_min: Option<f32>,
184 pub power_efficiency_ipw: Option<f32>,
186 pub recommended_power_mode: PowerMode,
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
192pub enum PowerMode {
193 MaxPerformance,
194 Balanced,
195 PowerSaver,
196 UltraLowPower,
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct MemoryAnalysis {
202 pub current_usage_bytes: u64,
204 pub peak_usage_bytes: u64,
206 pub available_bytes: u64,
208 pub fragmentation_percent: f32,
210 pub allocation_patterns: Vec<AllocationPattern>,
212 pub potential_leaks: Vec<MemoryLeak>,
214 pub gc_stats: Option<GCStats>,
216}
217
218#[derive(Debug, Clone, Serialize, Deserialize)]
220pub struct AllocationPattern {
221 pub size_bytes: u64,
223 pub frequency: u32,
225 pub average_lifetime_ms: f32,
227 pub source: String,
229}
230
231#[derive(Debug, Clone, Serialize, Deserialize)]
233pub struct MemoryLeak {
234 pub size_bytes: u64,
236 pub age_ms: u64,
238 pub source: String,
240 pub confidence: f32,
242}
243
244#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct GCStats {
247 pub gc_cycles: u32,
249 pub total_gc_time_ms: u64,
251 pub average_pause_ms: f32,
253 pub memory_reclaimed_bytes: u64,
255}
256
257#[derive(Debug, Clone, Serialize, Deserialize)]
259pub struct ProfilingReport {
260 pub metadata: ReportMetadata,
262 pub system_info: SystemInfo,
264 pub performance_summary: PerformanceSummary,
266 pub operation_profiles: Vec<OperationProfile>,
268 pub thermal_analysis: ThermalAnalysis,
270 pub power_analysis: PowerAnalysis,
272 pub memory_analysis: MemoryAnalysis,
274 pub metrics_timeline: Vec<PerformanceMetrics>,
276 pub recommendations: Vec<OptimizationRecommendation>,
278 pub bottlenecks: Vec<PerformanceBottleneck>,
280}
281
282#[derive(Debug, Clone, Serialize, Deserialize)]
284pub struct ReportMetadata {
285 pub session_id: String,
287 pub start_time: u64,
289 pub end_time: u64,
291 pub duration_ms: u64,
293 pub profiler_version: String,
295 pub model_info: Option<String>,
297}
298
299#[derive(Debug, Clone, Serialize, Deserialize)]
301pub struct SystemInfo {
302 pub platform: String,
304 pub device_model: String,
306 pub os_version: String,
308 pub cpu_arch: String,
310 pub total_memory_bytes: u64,
312 pub gpu_info: Option<String>,
314 pub available_backends: Vec<String>,
316}
317
318#[derive(Debug, Clone, Serialize, Deserialize)]
320pub struct PerformanceSummary {
321 pub avg_inference_latency_ms: f32,
323 pub p95_latency_ms: f32,
325 pub p99_latency_ms: f32,
327 pub avg_throughput_ips: f32,
329 pub peak_throughput_ips: f32,
331 pub avg_memory_usage_mb: f32,
333 pub peak_memory_usage_mb: f32,
335 pub avg_power_consumption_w: f32,
337 pub total_energy_consumed_j: f32,
339 pub efficiency_score: f32,
341}
342
343#[derive(Debug, Clone, Serialize, Deserialize)]
345pub struct OptimizationRecommendation {
346 pub recommendation_type: RecommendationType,
348 pub priority: RecommendationPriority,
350 pub description: String,
352 pub expected_improvement: String,
354 pub difficulty: ImplementationDifficulty,
356 pub affected_operations: Vec<String>,
358}
359
360#[derive(Debug, Clone, Serialize, Deserialize)]
362pub enum RecommendationType {
363 Quantization,
364 OperatorFusion,
365 MemoryOptimization,
366 PowerManagement,
367 ThermalManagement,
368 ModelCompression,
369 BatchSizeOptimization,
370 PrecisionTuning,
371 CacheOptimization,
372 ParallelizationStrategy,
373}
374
375#[derive(Debug, Clone, Serialize, Deserialize)]
377pub enum RecommendationPriority {
378 Critical,
379 High,
380 Medium,
381 Low,
382}
383
384#[derive(Debug, Clone, Serialize, Deserialize)]
386pub enum ImplementationDifficulty {
387 Easy, Medium, Hard, Expert, }
392
393#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct PerformanceBottleneck {
396 pub bottleneck_type: BottleneckType,
398 pub severity: f32,
400 pub affected_operations: Vec<String>,
402 pub description: String,
404 pub solutions: Vec<String>,
406 pub performance_impact_percent: f32,
408}
409
410#[derive(Debug, Clone, Serialize, Deserialize)]
412pub enum BottleneckType {
413 Compute,
414 Memory,
415 IO,
416 Thermal,
417 Power,
418 Network,
419 Synchronization,
420}
421
422pub struct AdvancedProfiler {
424 config: AdvancedProfilerConfig,
425 mobile_config: MobileConfig,
426 session_id: String,
427 start_time: Instant,
428 metrics_history: VecDeque<PerformanceMetrics>,
429 operation_profiles: Vec<OperationProfile>,
430 current_session: Option<ProfilingSession>,
431 baseline_metrics: Option<PerformanceMetrics>,
432}
433
434struct ProfilingSession {
436 id: String,
437 start_time: Instant,
438 active_operations: HashMap<String, Instant>,
439 memory_tracker: MemoryTracker,
440 thermal_monitor: ThermalMonitor,
441 power_monitor: PowerMonitor,
442}
443
444struct MemoryTracker {
446 allocations: HashMap<String, AllocationInfo>,
447 peak_usage: u64,
448 current_usage: u64,
449}
450
451struct AllocationInfo {
453 size: u64,
454 timestamp: Instant,
455 source: String,
456}
457
458struct ThermalMonitor {
460 temperature_history: VecDeque<f32>,
461 throttling_events: Vec<Instant>,
462 baseline_temp: f32,
463}
464
465struct PowerMonitor {
467 power_readings: VecDeque<f32>,
468 baseline_power: f32,
469 energy_consumed: f32,
470}
471
472impl AdvancedProfiler {
473 pub fn new(config: AdvancedProfilerConfig, mobile_config: MobileConfig) -> Self {
475 let session_id = format!(
476 "prof_{}",
477 std::time::SystemTime::now()
478 .duration_since(std::time::UNIX_EPOCH)
479 .unwrap_or_default()
480 .as_secs()
481 );
482
483 Self {
484 config,
485 mobile_config,
486 session_id,
487 start_time: Instant::now(),
488 metrics_history: VecDeque::with_capacity(1000),
489 operation_profiles: Vec::new(),
490 current_session: None,
491 baseline_metrics: None,
492 }
493 }
494
495 pub fn start_session(&mut self) -> Result<String> {
497 let session_id = format!(
498 "session_{}",
499 std::time::SystemTime::now()
500 .duration_since(std::time::UNIX_EPOCH)
501 .unwrap_or_default()
502 .as_secs()
503 );
504
505 let session = ProfilingSession {
506 id: session_id.clone(),
507 start_time: Instant::now(),
508 active_operations: HashMap::new(),
509 memory_tracker: MemoryTracker {
510 allocations: HashMap::new(),
511 peak_usage: 0,
512 current_usage: 0,
513 },
514 thermal_monitor: ThermalMonitor {
515 temperature_history: VecDeque::with_capacity(100),
516 throttling_events: Vec::new(),
517 baseline_temp: self.get_current_temperature(),
518 },
519 power_monitor: PowerMonitor {
520 power_readings: VecDeque::with_capacity(100),
521 baseline_power: self.get_current_power_consumption(),
522 energy_consumed: 0.0,
523 },
524 };
525
526 self.baseline_metrics = Some(self.capture_current_metrics()?);
528 self.current_session = Some(session);
529
530 Ok(session_id)
531 }
532
533 pub fn operation_start(
535 &mut self,
536 operation_name: &str,
537 operation_type: OperationType,
538 ) -> Result<()> {
539 if let Some(ref mut session) = self.current_session {
540 session.active_operations.insert(operation_name.to_string(), Instant::now());
541 }
542 Ok(())
543 }
544
545 pub fn operation_end(
547 &mut self,
548 operation_name: &str,
549 input_shapes: Vec<Vec<usize>>,
550 output_shape: Vec<usize>,
551 ) -> Result<()> {
552 let memory_after = self.get_memory_usage();
554
555 if let Some(ref mut session) = self.current_session {
556 if let Some(start_time) = session.active_operations.remove(operation_name) {
557 let execution_time = start_time.elapsed();
558
559 let memory_before = session.memory_tracker.current_usage;
561 let memory_allocated = memory_after.saturating_sub(memory_before);
562 let memory_freed = memory_before.saturating_sub(memory_after);
563
564 session.memory_tracker.current_usage = memory_after;
566 if memory_after > session.memory_tracker.peak_usage {
567 session.memory_tracker.peak_usage = memory_after;
568 }
569
570 let profile = OperationProfile {
572 operation_name: operation_name.to_string(),
573 operation_type: self.infer_operation_type(operation_name),
574 execution_time_us: execution_time.as_micros() as u64,
575 memory_allocated_bytes: memory_allocated,
576 memory_freed_bytes: memory_freed,
577 flops: self.estimate_flops(&input_shapes, &output_shape),
578 input_shapes,
579 output_shape,
580 gpu_kernel_time_us: self.get_gpu_kernel_time(operation_name, execution_time),
581 cache_hit_rate: self.estimate_cache_hit_rate(operation_name),
582 };
583
584 self.operation_profiles.push(profile);
585 }
586 }
587 Ok(())
588 }
589
590 pub fn capture_metrics(&mut self) -> Result<PerformanceMetrics> {
592 let metrics = self.capture_current_metrics()?;
593
594 self.metrics_history.push_back(metrics.clone());
596
597 while self.metrics_history.len() > self.config.max_history_length {
599 self.metrics_history.pop_front();
600 }
601
602 Ok(metrics)
603 }
604
605 pub fn generate_report(&self) -> Result<ProfilingReport> {
607 let end_time = Instant::now();
608 let duration = end_time.duration_since(self.start_time);
609
610 let report = ProfilingReport {
611 metadata: ReportMetadata {
612 session_id: self.session_id.clone(),
613 start_time: self.start_time.elapsed().as_millis() as u64,
614 end_time: end_time.elapsed().as_millis() as u64,
615 duration_ms: duration.as_millis() as u64,
616 profiler_version: "1.0.0".to_string(),
617 model_info: None,
618 },
619 system_info: self.get_system_info(),
620 performance_summary: self.calculate_performance_summary(),
621 operation_profiles: self.operation_profiles.clone(),
622 thermal_analysis: self.analyze_thermal_performance(),
623 power_analysis: self.analyze_power_consumption(),
624 memory_analysis: self.analyze_memory_usage(),
625 metrics_timeline: self.metrics_history.clone().into(),
626 recommendations: self.generate_recommendations(),
627 bottlenecks: self.identify_bottlenecks(),
628 };
629
630 Ok(report)
631 }
632
633 pub fn export_report(
635 &self,
636 report: &ProfilingReport,
637 format: ProfilerOutputFormat,
638 ) -> Result<String> {
639 match format {
640 ProfilerOutputFormat::Json => serde_json::to_string_pretty(report)
641 .map_err(|e| TrustformersError::serialization_error(e.to_string()).into()),
642 ProfilerOutputFormat::Csv => {
643 self.export_csv_report(report)
645 },
646 ProfilerOutputFormat::Flamegraph => {
647 self.export_flamegraph(report)
649 },
650 ProfilerOutputFormat::Chrome => {
651 self.export_chrome_format(report)
653 },
654 ProfilerOutputFormat::Custom(format_name) => Err(TrustformersError::invalid_input(
655 format!("Unsupported format: {}", format_name),
656 )
657 .into()),
658 }
659 }
660
661 pub fn get_realtime_recommendations(&self) -> Vec<OptimizationRecommendation> {
663 let mut recommendations = Vec::new();
664
665 if let Some(current_metrics) = self.metrics_history.back() {
666 if current_metrics.memory_usage > (4 * 1024 * 1024 * 1024) {
668 recommendations.push(OptimizationRecommendation {
670 recommendation_type: RecommendationType::MemoryOptimization,
671 priority: RecommendationPriority::High,
672 description: "High memory usage detected. Consider enabling memory pooling or reducing batch size.".to_string(),
673 expected_improvement: "20-40% memory reduction".to_string(),
674 difficulty: ImplementationDifficulty::Medium,
675 affected_operations: vec!["All operations".to_string()],
676 });
677 }
678
679 if let Some(temp) = current_metrics.temperature {
681 if temp > 70.0 {
682 recommendations.push(OptimizationRecommendation {
684 recommendation_type: RecommendationType::ThermalManagement,
685 priority: RecommendationPriority::Critical,
686 description: "High temperature detected. Enable thermal throttling or reduce precision.".to_string(),
687 expected_improvement: "Temperature reduction and sustained performance".to_string(),
688 difficulty: ImplementationDifficulty::Easy,
689 affected_operations: vec!["Compute-intensive operations".to_string()],
690 });
691 }
692 }
693
694 if let Some(power) = current_metrics.power_consumption {
696 if power > 5.0 {
697 recommendations.push(OptimizationRecommendation {
699 recommendation_type: RecommendationType::PowerManagement,
700 priority: RecommendationPriority::Medium,
701 description: "High power consumption detected. Consider switching to power-saving mode.".to_string(),
702 expected_improvement: "20-30% power reduction".to_string(),
703 difficulty: ImplementationDifficulty::Easy,
704 affected_operations: vec!["All operations".to_string()],
705 });
706 }
707 }
708 }
709
710 recommendations
711 }
712
713 fn capture_current_metrics(&self) -> Result<PerformanceMetrics> {
716 Ok(PerformanceMetrics {
717 timestamp: std::time::SystemTime::now()
718 .duration_since(std::time::UNIX_EPOCH)
719 .unwrap_or_default()
720 .as_secs(),
721 cpu_usage: self.get_cpu_usage(),
722 memory_usage: self.get_memory_usage(),
723 peak_memory: self.get_peak_memory(),
724 gpu_usage: self.get_gpu_usage(),
725 gpu_memory: self.get_gpu_memory(),
726 temperature: Some(self.get_current_temperature()),
727 battery_level: self.get_battery_level(),
728 power_consumption: Some(self.get_current_power_consumption()),
729 network_sent_bytes: self.get_network_sent(),
730 network_received_bytes: self.get_network_received(),
731 fps: self.calculate_fps(),
732 inference_latency_ms: self.calculate_average_latency(),
733 throughput_ips: self.calculate_throughput(),
734 })
735 }
736
737 fn get_system_info(&self) -> SystemInfo {
738 SystemInfo {
739 platform: match self.mobile_config.platform {
740 MobilePlatform::Ios => "iOS".to_string(),
741 MobilePlatform::Android => "Android".to_string(),
742 MobilePlatform::Generic => "Generic".to_string(),
743 },
744 device_model: self.detect_device_model(),
745 os_version: self.detect_os_version(),
746 cpu_arch: std::env::consts::ARCH.to_string(),
747 total_memory_bytes: (self.mobile_config.max_memory_mb * 1024 * 1024) as u64,
748 gpu_info: self.detect_gpu_info(),
749 available_backends: vec![format!("{:?}", self.mobile_config.backend)],
750 }
751 }
752
753 fn calculate_performance_summary(&self) -> PerformanceSummary {
754 if self.metrics_history.is_empty() {
755 return PerformanceSummary {
756 avg_inference_latency_ms: 0.0,
757 p95_latency_ms: 0.0,
758 p99_latency_ms: 0.0,
759 avg_throughput_ips: 0.0,
760 peak_throughput_ips: 0.0,
761 avg_memory_usage_mb: 0.0,
762 peak_memory_usage_mb: 0.0,
763 avg_power_consumption_w: 0.0,
764 total_energy_consumed_j: 0.0,
765 efficiency_score: 0.0,
766 };
767 }
768
769 let total_metrics = self.metrics_history.len() as f32;
770
771 let avg_memory = self.metrics_history.iter().map(|m| m.memory_usage as f32).sum::<f32>()
772 / total_metrics
773 / (1024.0 * 1024.0); let peak_memory = self.metrics_history.iter().map(|m| m.peak_memory).max().unwrap_or(0)
776 as f32
777 / (1024.0 * 1024.0); let avg_power =
780 self.metrics_history.iter().filter_map(|m| m.power_consumption).sum::<f32>()
781 / total_metrics;
782
783 let latencies: Vec<f32> = self.operation_profiles.iter()
785 .map(|op| op.execution_time_us as f32 / 1000.0) .collect();
787
788 let (avg_latency, p95_latency, p99_latency) =
789 self.calculate_latency_percentiles(&latencies);
790
791 let (avg_throughput, peak_throughput) = self.calculate_throughput_stats();
793
794 let efficiency_score = self.calculate_efficiency_score(avg_latency, avg_power, avg_memory);
796
797 PerformanceSummary {
798 avg_inference_latency_ms: avg_latency,
799 p95_latency_ms: p95_latency,
800 p99_latency_ms: p99_latency,
801 avg_throughput_ips: avg_throughput,
802 peak_throughput_ips: peak_throughput,
803 avg_memory_usage_mb: avg_memory,
804 peak_memory_usage_mb: peak_memory,
805 avg_power_consumption_w: avg_power,
806 total_energy_consumed_j: avg_power * self.start_time.elapsed().as_secs_f32(),
807 efficiency_score,
808 }
809 }
810
811 fn analyze_thermal_performance(&self) -> ThermalAnalysis {
812 let current_temp = self.get_current_temperature();
813 let is_throttling = current_temp > 80.0; let trend = if current_temp > 75.0 {
816 TemperatureTrend::Critical
817 } else if current_temp > 65.0 {
818 TemperatureTrend::Rising
819 } else if current_temp > 45.0 {
820 TemperatureTrend::Stable
821 } else {
822 TemperatureTrend::Cooling
823 };
824
825 let recommendation = match trend {
826 TemperatureTrend::Critical => ThermalRecommendation::PauseInference,
827 TemperatureTrend::Rising => ThermalRecommendation::ReduceFrequency,
828 _ => ThermalRecommendation::Continue,
829 };
830
831 ThermalAnalysis {
832 temperature_zones: {
833 let mut zones = HashMap::new();
834 zones.insert("CPU".to_string(), current_temp);
835 zones.insert("GPU".to_string(), current_temp - 5.0); zones
837 },
838 is_throttling,
839 temperature_trend: trend,
840 time_to_throttling_ms: if current_temp > 70.0 { Some(30000) } else { None },
841 recommended_action: recommendation,
842 }
843 }
844
845 fn analyze_power_consumption(&self) -> PowerAnalysis {
846 let current_power = self.get_current_power_consumption();
847 let avg_power =
848 self.metrics_history.iter().filter_map(|m| m.power_consumption).sum::<f32>()
849 / self.metrics_history.len() as f32;
850 let peak_power = self
851 .metrics_history
852 .iter()
853 .filter_map(|m| m.power_consumption)
854 .fold(0.0f32, |acc, x| acc.max(x));
855
856 PowerAnalysis {
857 current_power_w: current_power,
858 average_power_w: avg_power,
859 peak_power_w: peak_power,
860 battery_life_remaining_min: self.estimate_battery_life(),
861 power_efficiency_ipw: Some(20.0 / current_power), recommended_power_mode: if current_power > 5.0 {
863 PowerMode::PowerSaver
864 } else if current_power > 3.0 {
865 PowerMode::Balanced
866 } else {
867 PowerMode::MaxPerformance
868 },
869 }
870 }
871
872 fn analyze_memory_usage(&self) -> MemoryAnalysis {
873 let current_usage = self.get_memory_usage();
874 let peak_usage = self.get_peak_memory();
875 let available = (self.mobile_config.max_memory_mb * 1024 * 1024) as u64 - current_usage;
876
877 MemoryAnalysis {
878 current_usage_bytes: current_usage,
879 peak_usage_bytes: peak_usage,
880 available_bytes: available,
881 fragmentation_percent: self.calculate_memory_fragmentation(),
882 allocation_patterns: self.analyze_allocation_patterns(),
883 potential_leaks: self.detect_memory_leaks(),
884 gc_stats: self.calculate_gc_stats(),
885 }
886 }
887
888 fn generate_recommendations(&self) -> Vec<OptimizationRecommendation> {
889 let mut recommendations = Vec::new();
890
891 recommendations.push(OptimizationRecommendation {
893 recommendation_type: RecommendationType::Quantization,
894 priority: RecommendationPriority::High,
895 description:
896 "Consider using INT8 quantization for better performance and lower memory usage."
897 .to_string(),
898 expected_improvement: "50% memory reduction, 2x speed improvement".to_string(),
899 difficulty: ImplementationDifficulty::Medium,
900 affected_operations: ["Linear", "Convolution"].iter().map(|s| s.to_string()).collect(),
901 });
902
903 recommendations.push(OptimizationRecommendation {
905 recommendation_type: RecommendationType::OperatorFusion,
906 priority: RecommendationPriority::Medium,
907 description: "Fuse consecutive operators to reduce memory transfers and improve cache efficiency.".to_string(),
908 expected_improvement: "15-25% latency reduction".to_string(),
909 difficulty: ImplementationDifficulty::Easy,
910 affected_operations: ["Conv+BatchNorm", "Linear+Activation"].iter().map(|s| s.to_string()).collect(),
911 });
912
913 recommendations
914 }
915
916 fn identify_bottlenecks(&self) -> Vec<PerformanceBottleneck> {
917 let mut bottlenecks = Vec::new();
918
919 if self.get_memory_usage() > (self.mobile_config.max_memory_mb * 1024 * 1024 * 3 / 4) as u64
921 {
922 bottlenecks.push(PerformanceBottleneck {
923 bottleneck_type: BottleneckType::Memory,
924 severity: 75.0,
925 affected_operations: vec!["All operations".to_string()],
926 description: "High memory usage may cause performance degradation.".to_string(),
927 solutions: vec![
928 "Enable memory pooling".to_string(),
929 "Reduce batch size".to_string(),
930 "Use quantization".to_string(),
931 ],
932 performance_impact_percent: 25.0,
933 });
934 }
935
936 if self.get_current_temperature() > 70.0 {
938 bottlenecks.push(PerformanceBottleneck {
939 bottleneck_type: BottleneckType::Thermal,
940 severity: 85.0,
941 affected_operations: vec!["Compute-intensive operations".to_string()],
942 description: "High temperature causing thermal throttling.".to_string(),
943 solutions: vec![
944 "Reduce computation frequency".to_string(),
945 "Enable thermal management".to_string(),
946 "Switch to lower precision".to_string(),
947 ],
948 performance_impact_percent: 40.0,
949 });
950 }
951
952 bottlenecks
953 }
954
955 fn get_cpu_usage(&self) -> f32 {
957 let recent_ops = self
959 .operation_profiles
960 .iter()
961 .rev()
962 .take(10)
963 .map(|op| op.execution_time_us)
964 .sum::<u64>();
965
966 let base_usage = 25.0;
968 let activity_factor = (recent_ops as f32 / 100_000.0).min(50.0); base_usage + activity_factor
970 }
971
972 fn get_memory_usage(&self) -> u64 {
973 let base_memory = (self.mobile_config.max_memory_mb as u64 * 1024 * 1024) / 4; let operation_memory = self
976 .operation_profiles
977 .iter()
978 .map(|op| op.memory_allocated_bytes.saturating_sub(op.memory_freed_bytes))
979 .sum::<u64>();
980
981 base_memory + operation_memory
982 }
983
984 fn get_peak_memory(&self) -> u64 {
985 let current = self.get_memory_usage();
986 let historical_peak =
987 self.metrics_history.iter().map(|m| m.peak_memory).max().unwrap_or(current);
988
989 current.max(historical_peak)
990 }
991
992 fn get_gpu_usage(&self) -> Option<f32> {
993 match self.mobile_config.backend {
994 MobileBackend::Metal | MobileBackend::Vulkan | MobileBackend::OpenCL => {
995 let gpu_ops = self
997 .operation_profiles
998 .iter()
999 .filter(|op| {
1000 matches!(
1001 op.operation_type,
1002 OperationType::Convolution
1003 | OperationType::LinearTransform
1004 | OperationType::Attention
1005 )
1006 })
1007 .count();
1008
1009 let base_usage = 20.0;
1010 let activity_usage = (gpu_ops as f32 * 5.0).min(60.0);
1011 Some(base_usage + activity_usage)
1012 },
1013 _ => None,
1014 }
1015 }
1016
1017 fn get_gpu_memory(&self) -> Option<u64> {
1018 match self.mobile_config.backend {
1019 MobileBackend::Metal | MobileBackend::Vulkan | MobileBackend::OpenCL => {
1020 let gpu_memory = self
1022 .operation_profiles
1023 .iter()
1024 .filter(|op| {
1025 matches!(
1026 op.operation_type,
1027 OperationType::Convolution | OperationType::LinearTransform
1028 )
1029 })
1030 .map(|op| {
1031 let input_size: usize =
1032 op.input_shapes.iter().map(|s| s.iter().product::<usize>()).sum();
1033 let output_size: usize = op.output_shape.iter().product();
1034 ((input_size + output_size) * 4) as u64 })
1036 .sum::<u64>();
1037
1038 Some((200 * 1024 * 1024) + gpu_memory) },
1040 _ => None,
1041 }
1042 }
1043
1044 fn get_current_temperature(&self) -> f32 {
1045 let cpu_usage = self.get_cpu_usage();
1047 let gpu_usage = self.get_gpu_usage().unwrap_or(0.0);
1048 let duration_minutes = self.start_time.elapsed().as_secs() as f32 / 60.0;
1049
1050 let base_temp = 35.0; let cpu_heat = cpu_usage * 0.3; let gpu_heat = gpu_usage * 0.2; let duration_heat = duration_minutes * 0.5; (base_temp + cpu_heat + gpu_heat + duration_heat).min(85.0) }
1057
1058 fn get_battery_level(&self) -> Option<f32> {
1059 match self.mobile_config.platform {
1060 MobilePlatform::Ios | MobilePlatform::Android => {
1061 let power = self.get_current_power_consumption();
1063 let duration_hours = self.start_time.elapsed().as_secs() as f32 / 3600.0;
1064 let initial_level = 85.0;
1065 let drain_rate = power * 2.0; Some((initial_level - (drain_rate * duration_hours)).max(5.0))
1068 },
1069 _ => None,
1070 }
1071 }
1072
1073 fn get_current_power_consumption(&self) -> f32 {
1074 let cpu_usage = self.get_cpu_usage();
1076 let gpu_usage = self.get_gpu_usage().unwrap_or(0.0);
1077
1078 let base_power = 1.0; let cpu_power = cpu_usage * 0.02; let gpu_power = gpu_usage * 0.03; base_power + cpu_power + gpu_power
1083 }
1084
1085 fn get_network_sent(&self) -> Option<u64> {
1086 if self.config.enable_network_tracking {
1088 Some(self.operation_profiles.len() as u64 * 512) } else {
1090 None
1091 }
1092 }
1093
1094 fn get_network_received(&self) -> Option<u64> {
1095 if self.config.enable_network_tracking {
1097 Some(self.operation_profiles.len() as u64 * 1024) } else {
1099 None
1100 }
1101 }
1102
1103 fn estimate_battery_life(&self) -> Option<f32> {
1104 if let Some(battery_level) = self.get_battery_level() {
1105 let power_consumption = self.get_current_power_consumption();
1106 let battery_capacity_wh = match self.mobile_config.platform {
1107 MobilePlatform::Ios => 15.0, MobilePlatform::Android => 20.0, _ => 10.0,
1110 };
1111
1112 let remaining_capacity = (battery_level / 100.0) * battery_capacity_wh;
1113 let estimated_hours = remaining_capacity / power_consumption;
1114
1115 Some(estimated_hours * 60.0) } else {
1117 None
1118 }
1119 }
1120
1121 fn infer_operation_type(&self, operation_name: &str) -> OperationType {
1122 let name_lower = operation_name.to_lowercase();
1123 if name_lower.contains("conv") {
1124 OperationType::Convolution
1125 } else if name_lower.contains("linear")
1126 || name_lower.contains("dense")
1127 || name_lower.contains("matmul")
1128 {
1129 OperationType::LinearTransform
1130 } else if name_lower.contains("attention") || name_lower.contains("attn") {
1131 OperationType::Attention
1132 } else if name_lower.contains("norm")
1133 || name_lower.contains("batch")
1134 || name_lower.contains("layer")
1135 {
1136 OperationType::Normalization
1137 } else if name_lower.contains("relu")
1138 || name_lower.contains("gelu")
1139 || name_lower.contains("sigmoid")
1140 || name_lower.contains("tanh")
1141 || name_lower.contains("softmax")
1142 {
1143 OperationType::Activation
1144 } else if name_lower.contains("pool") {
1145 OperationType::Pooling
1146 } else if name_lower.contains("quantize") {
1147 OperationType::Quantization
1148 } else if name_lower.contains("dequantize") {
1149 OperationType::Dequantization
1150 } else if name_lower.contains("copy") || name_lower.contains("memcpy") {
1151 OperationType::MemoryCopy
1152 } else if name_lower.contains("transfer")
1153 || name_lower.contains("upload")
1154 || name_lower.contains("download")
1155 {
1156 OperationType::DataTransfer
1157 } else {
1158 OperationType::Custom(operation_name.to_string())
1159 }
1160 }
1161
1162 fn estimate_flops(&self, input_shapes: &[Vec<usize>], output_shape: &[usize]) -> Option<u64> {
1163 if input_shapes.is_empty() || output_shape.is_empty() {
1165 return None;
1166 }
1167
1168 let input_size: usize = input_shapes[0].iter().product();
1169 let output_size: usize = output_shape.iter().product();
1170
1171 Some((2 * input_size * output_size) as u64)
1173 }
1174
1175 fn get_gpu_kernel_time(&self, operation_name: &str, cpu_time: Duration) -> Option<u64> {
1178 if self.get_gpu_usage().is_some() {
1180 let operation_type = self.infer_operation_type(operation_name);
1181 let gpu_efficiency = match operation_type {
1182 OperationType::Convolution => 0.3, OperationType::LinearTransform => 0.4, OperationType::Attention => 0.5, OperationType::Activation => 0.8, _ => 0.9, };
1188
1189 Some((cpu_time.as_micros() as f64 * gpu_efficiency) as u64)
1190 } else {
1191 None
1192 }
1193 }
1194
1195 fn estimate_cache_hit_rate(&self, operation_name: &str) -> Option<f32> {
1196 let operation_type = self.infer_operation_type(operation_name);
1198 let base_hit_rate = match operation_type {
1199 OperationType::Convolution => 0.85, OperationType::LinearTransform => 0.75, OperationType::Attention => 0.60, OperationType::Activation => 0.90, OperationType::Normalization => 0.80, _ => 0.70, };
1206
1207 let recent_memory_pressure = self
1209 .metrics_history
1210 .iter()
1211 .rev()
1212 .take(5)
1213 .map(|m| {
1214 m.memory_usage as f32 / (self.mobile_config.max_memory_mb as f32 * 1024.0 * 1024.0)
1215 })
1216 .sum::<f32>()
1217 / 5.0;
1218
1219 let pressure_penalty = recent_memory_pressure * 0.2; Some((base_hit_rate - pressure_penalty).max(0.1))
1221 }
1222
1223 fn calculate_fps(&self) -> Option<f32> {
1224 if self.operation_profiles.len() < 2 {
1225 return None;
1226 }
1227
1228 let recent_operations = self.operation_profiles.iter()
1230 .rev()
1231 .take(30) .collect::<Vec<_>>();
1233
1234 if recent_operations.len() < 2 {
1235 return None;
1236 }
1237
1238 let total_time_ms = recent_operations
1239 .iter()
1240 .map(|op| op.execution_time_us as f32 / 1000.0)
1241 .sum::<f32>();
1242
1243 if total_time_ms > 0.0 {
1244 Some(1000.0 * recent_operations.len() as f32 / total_time_ms)
1245 } else {
1246 None
1247 }
1248 }
1249
1250 fn calculate_average_latency(&self) -> Option<f32> {
1251 if self.operation_profiles.is_empty() {
1252 return None;
1253 }
1254
1255 let total_latency = self.operation_profiles.iter()
1256 .map(|op| op.execution_time_us as f32 / 1000.0) .sum::<f32>();
1258
1259 Some(total_latency / self.operation_profiles.len() as f32)
1260 }
1261
1262 fn calculate_throughput(&self) -> Option<f32> {
1263 if self.operation_profiles.is_empty() || self.start_time.elapsed().as_secs() == 0 {
1264 return None;
1265 }
1266
1267 let elapsed_seconds = self.start_time.elapsed().as_secs_f32();
1268 Some(self.operation_profiles.len() as f32 / elapsed_seconds)
1269 }
1270
1271 fn detect_device_model(&self) -> String {
1272 match self.mobile_config.platform {
1273 MobilePlatform::Ios => {
1274 "iPhone 15 Pro".to_string() },
1277 MobilePlatform::Android => {
1278 "Samsung Galaxy S24".to_string() },
1281 MobilePlatform::Generic => {
1282 std::env::var("DEVICE_MODEL").unwrap_or_else(|_| "Generic Device".to_string())
1283 },
1284 }
1285 }
1286
1287 fn detect_os_version(&self) -> String {
1288 match self.mobile_config.platform {
1289 MobilePlatform::Ios => {
1290 "iOS 17.5".to_string() },
1292 MobilePlatform::Android => {
1293 "Android 14".to_string() },
1295 MobilePlatform::Generic => std::env::consts::OS.to_string(),
1296 }
1297 }
1298
1299 fn detect_gpu_info(&self) -> Option<String> {
1300 match self.mobile_config.backend {
1301 MobileBackend::Metal => Some("Apple A17 Pro GPU".to_string()),
1302 MobileBackend::Vulkan => Some("Adreno 750 GPU".to_string()),
1303 MobileBackend::OpenCL => Some("Mali-G78 GPU".to_string()),
1304 _ => None,
1305 }
1306 }
1307
1308 fn calculate_latency_percentiles(&self, latencies: &[f32]) -> (f32, f32, f32) {
1309 if latencies.is_empty() {
1310 return (0.0, 0.0, 0.0);
1311 }
1312
1313 let mut sorted = latencies.to_vec();
1314 sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1315
1316 let avg = sorted.iter().sum::<f32>() / sorted.len() as f32;
1317 let p95_idx = ((sorted.len() as f32 * 0.95) as usize).min(sorted.len() - 1);
1318 let p99_idx = ((sorted.len() as f32 * 0.99) as usize).min(sorted.len() - 1);
1319
1320 let p95 = sorted[p95_idx];
1321 let p99 = sorted[p99_idx];
1322
1323 (avg, p95, p99)
1324 }
1325
1326 fn calculate_throughput_stats(&self) -> (f32, f32) {
1327 if self.operation_profiles.is_empty() {
1328 return (0.0, 0.0);
1329 }
1330
1331 let window_size = 10;
1333 let mut throughputs = Vec::new();
1334
1335 for window_start in 0..self.operation_profiles.len().saturating_sub(window_size - 1) {
1336 let window_end = (window_start + window_size).min(self.operation_profiles.len());
1337 let window_ops = &self.operation_profiles[window_start..window_end];
1338
1339 let total_time_s = window_ops
1340 .iter()
1341 .map(|op| op.execution_time_us as f32 / 1_000_000.0)
1342 .sum::<f32>();
1343
1344 if total_time_s > 0.0 {
1345 throughputs.push(window_ops.len() as f32 / total_time_s);
1346 }
1347 }
1348
1349 if throughputs.is_empty() {
1350 return (0.0, 0.0);
1351 }
1352
1353 let avg_throughput = throughputs.iter().sum::<f32>() / throughputs.len() as f32;
1354 let peak_throughput = throughputs.iter().fold(0.0f32, |acc, &x| acc.max(x));
1355
1356 (avg_throughput, peak_throughput)
1357 }
1358
1359 fn calculate_efficiency_score(
1360 &self,
1361 avg_latency: f32,
1362 avg_power: f32,
1363 avg_memory_mb: f32,
1364 ) -> f32 {
1365 let mut score = 100.0;
1367
1368 let latency_penalty = (avg_latency / 100.0).min(50.0); score -= latency_penalty;
1371
1372 let power_penalty = (avg_power / 10.0 * 20.0).min(30.0); score -= power_penalty;
1375
1376 let memory_ratio = avg_memory_mb / (self.mobile_config.max_memory_mb as f32);
1378 let memory_penalty = (memory_ratio * 20.0).min(20.0); score -= memory_penalty;
1380
1381 score.max(0.0)
1382 }
1383
1384 fn calculate_memory_fragmentation(&self) -> f32 {
1385 let total_allocations =
1387 self.operation_profiles.iter().map(|op| op.memory_allocated_bytes).sum::<u64>();
1388
1389 let total_deallocations =
1390 self.operation_profiles.iter().map(|op| op.memory_freed_bytes).sum::<u64>();
1391
1392 if total_allocations > 0 {
1393 let allocation_efficiency = total_deallocations as f32 / total_allocations as f32;
1394 let fragmentation = (1.0 - allocation_efficiency.min(1.0)) * 100.0;
1395 fragmentation.min(25.0) } else {
1397 0.0
1398 }
1399 }
1400
1401 fn analyze_allocation_patterns(&self) -> Vec<AllocationPattern> {
1402 let mut patterns = std::collections::HashMap::new();
1403
1404 for op in &self.operation_profiles {
1406 if op.memory_allocated_bytes > 0 {
1407 let size_bucket = if op.memory_allocated_bytes < 1024 {
1408 "Small (<1KB)".to_string()
1409 } else if op.memory_allocated_bytes < 1024 * 1024 {
1410 "Medium (1KB-1MB)".to_string()
1411 } else {
1412 "Large (>1MB)".to_string()
1413 };
1414
1415 let pattern = patterns.entry(size_bucket).or_insert(AllocationPattern {
1416 size_bytes: 0,
1417 frequency: 0,
1418 average_lifetime_ms: 0.0,
1419 source: "Unknown".to_string(),
1420 });
1421
1422 pattern.frequency += 1;
1423 pattern.size_bytes = op.memory_allocated_bytes; pattern.average_lifetime_ms = op.execution_time_us as f32 / 1000.0; pattern.source = format!("{:?}", op.operation_type);
1426 }
1427 }
1428
1429 patterns.into_values().collect()
1430 }
1431
1432 fn detect_memory_leaks(&self) -> Vec<MemoryLeak> {
1433 let mut potential_leaks = Vec::new();
1434
1435 for op in &self.operation_profiles {
1437 if op.memory_allocated_bytes > 1024 * 1024 && op.memory_freed_bytes == 0 {
1438 potential_leaks.push(MemoryLeak {
1439 size_bytes: op.memory_allocated_bytes,
1440 age_ms: op.execution_time_us / 1000, source: op.operation_name.clone(),
1442 confidence: if op.memory_allocated_bytes > 10 * 1024 * 1024 {
1443 0.8
1444 } else {
1445 0.4
1446 },
1447 });
1448 }
1449 }
1450
1451 potential_leaks
1452 }
1453
1454 fn calculate_gc_stats(&self) -> Option<GCStats> {
1455 match self.mobile_config.platform {
1457 MobilePlatform::Android => {
1458 let operations_count = self.operation_profiles.len() as u32;
1460 let estimated_gc_cycles = operations_count / 50; Some(GCStats {
1463 gc_cycles: estimated_gc_cycles,
1464 total_gc_time_ms: estimated_gc_cycles as u64 * 5, average_pause_ms: 5.0,
1466 memory_reclaimed_bytes: self
1467 .operation_profiles
1468 .iter()
1469 .map(|op| op.memory_freed_bytes)
1470 .sum::<u64>(),
1471 })
1472 },
1473 _ => None, }
1475 }
1476
1477 fn export_csv_report(&self, report: &ProfilingReport) -> Result<String> {
1478 let mut csv = String::new();
1479
1480 csv.push_str("timestamp,cpu_usage,memory_usage,temperature,power_consumption\n");
1482
1483 for metric in &report.metrics_timeline {
1485 csv.push_str(&format!(
1486 "{},{},{},{},{}\n",
1487 metric.timestamp,
1488 metric.cpu_usage,
1489 metric.memory_usage,
1490 metric.temperature.unwrap_or(0.0),
1491 metric.power_consumption.unwrap_or(0.0)
1492 ));
1493 }
1494
1495 Ok(csv)
1496 }
1497
1498 fn export_flamegraph(&self, report: &ProfilingReport) -> Result<String> {
1499 let mut flamegraph_data = String::new();
1501 flamegraph_data.push_str("# Flamegraph Data\n");
1502
1503 let mut stack_traces = std::collections::HashMap::new();
1505
1506 for op in &report.operation_profiles {
1507 let stack = format!("{:?};{}", op.operation_type, op.operation_name);
1508 *stack_traces.entry(stack).or_insert(0u64) += op.execution_time_us;
1509 }
1510
1511 let mut sorted_traces: Vec<_> = stack_traces.into_iter().collect();
1513 sorted_traces.sort_by_key(|item| std::cmp::Reverse(item.1));
1514
1515 for (stack, time_us) in sorted_traces {
1516 flamegraph_data.push_str(&format!("{} {}\n", stack, time_us));
1517 }
1518
1519 Ok(flamegraph_data)
1520 }
1521
1522 fn export_chrome_format(&self, report: &ProfilingReport) -> Result<String> {
1523 let mut events = Vec::new();
1525
1526 events.push(serde_json::json!({
1528 "name": "process_name",
1529 "ph": "M",
1530 "pid": 1,
1531 "args": {
1532 "name": "TrustformeRS Mobile Profiler"
1533 }
1534 }));
1535
1536 events.push(serde_json::json!({
1538 "name": "thread_name",
1539 "ph": "M",
1540 "pid": 1,
1541 "tid": 1,
1542 "args": {
1543 "name": "Main Thread"
1544 }
1545 }));
1546
1547 let mut current_time = 0u64;
1549 for op in &report.operation_profiles {
1550 events.push(serde_json::json!({
1552 "name": op.operation_name,
1553 "cat": format!("{:?}", op.operation_type),
1554 "ph": "B",
1555 "ts": current_time,
1556 "pid": 1,
1557 "tid": 1,
1558 "args": {
1559 "input_shapes": op.input_shapes,
1560 "output_shape": op.output_shape,
1561 "flops": op.flops
1562 }
1563 }));
1564
1565 events.push(serde_json::json!({
1567 "name": op.operation_name,
1568 "cat": format!("{:?}", op.operation_type),
1569 "ph": "E",
1570 "ts": current_time + op.execution_time_us,
1571 "pid": 1,
1572 "tid": 1
1573 }));
1574
1575 current_time += op.execution_time_us + 100; }
1577
1578 let chrome_trace = serde_json::json!({
1579 "traceEvents": events,
1580 "displayTimeUnit": "ms",
1581 "otherData": {
1582 "version": "Chrome Trace Format",
1583 "creator": "TrustformeRS Mobile Profiler"
1584 }
1585 });
1586
1587 serde_json::to_string_pretty(&chrome_trace)
1588 .map_err(|e| TrustformersError::serialization_error(e.to_string()).into())
1589 }
1590}
1591
1592#[cfg(test)]
1593mod tests {
1594 use super::*;
1595
1596 #[test]
1597 fn test_profiler_creation() {
1598 let config = AdvancedProfilerConfig::default();
1599 let mobile_config = MobileConfig::default();
1600 let profiler = AdvancedProfiler::new(config, mobile_config);
1601 assert!(!profiler.session_id.is_empty());
1602 }
1603
1604 #[test]
1605 fn test_metrics_capture() {
1606 let config = AdvancedProfilerConfig::default();
1607 let mobile_config = MobileConfig::default();
1608 let mut profiler = AdvancedProfiler::new(config, mobile_config);
1609
1610 let metrics = profiler.capture_metrics();
1611 assert!(metrics.is_ok());
1612 assert_eq!(profiler.metrics_history.len(), 1);
1613 }
1614
1615 #[test]
1616 fn test_session_management() {
1617 let config = AdvancedProfilerConfig::default();
1618 let mobile_config = MobileConfig::default();
1619 let mut profiler = AdvancedProfiler::new(config, mobile_config);
1620
1621 let session_id = profiler.start_session();
1622 assert!(session_id.is_ok());
1623 assert!(profiler.current_session.is_some());
1624 }
1625
1626 #[test]
1627 fn test_operation_profiling() {
1628 let config = AdvancedProfilerConfig::default();
1629 let mobile_config = MobileConfig::default();
1630 let mut profiler = AdvancedProfiler::new(config, mobile_config);
1631
1632 let _ = profiler.start_session();
1633 let _ = profiler.operation_start("test_op", OperationType::LinearTransform);
1634 std::thread::sleep(std::time::Duration::from_millis(10));
1635 let _ = profiler.operation_end("test_op", vec![vec![32, 768]], vec![32, 10]);
1636
1637 assert_eq!(profiler.operation_profiles.len(), 1);
1638 }
1639
1640 #[test]
1641 fn test_report_generation() {
1642 let config = AdvancedProfilerConfig::default();
1643 let mobile_config = MobileConfig::default();
1644 let mut profiler = AdvancedProfiler::new(config, mobile_config);
1645
1646 let _ = profiler.capture_metrics();
1647 let report = profiler.generate_report();
1648 assert!(report.is_ok());
1649 }
1650
1651 #[test]
1652 fn test_recommendations() {
1653 let config = AdvancedProfilerConfig::default();
1654 let mobile_config = MobileConfig::default();
1655 let mut profiler = AdvancedProfiler::new(config, mobile_config);
1656
1657 let high_memory_metrics = PerformanceMetrics {
1659 timestamp: std::time::SystemTime::now()
1660 .duration_since(std::time::UNIX_EPOCH)
1661 .expect("Operation failed")
1662 .as_secs(),
1663 cpu_usage: 50.0,
1664 memory_usage: 5 * 1024 * 1024 * 1024, peak_memory: 5 * 1024 * 1024 * 1024,
1666 gpu_usage: Some(30.0),
1667 gpu_memory: Some(2 * 1024 * 1024 * 1024),
1668 temperature: Some(75.0), battery_level: Some(50.0),
1670 power_consumption: Some(6.0), network_sent_bytes: Some(1024 * 1024),
1672 network_received_bytes: Some(1024 * 1024),
1673 fps: Some(30.0),
1674 inference_latency_ms: Some(100.0),
1675 throughput_ips: Some(10.0),
1676 };
1677
1678 profiler.metrics_history.push_back(high_memory_metrics);
1679
1680 let recommendations = profiler.get_realtime_recommendations();
1681 assert!(!recommendations.is_empty());
1682 }
1683}