|
| 1 | +# Performance Metrics API |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +Code Guardian provides comprehensive performance metrics through the `AdvancedScanMetrics` struct and related APIs. This documentation covers how to access, interpret, and utilize performance data. |
| 6 | + |
| 7 | +## Core Types |
| 8 | + |
| 9 | +### AdvancedScanMetrics |
| 10 | + |
| 11 | +```rust |
| 12 | +pub struct AdvancedScanMetrics { |
| 13 | + pub total_files_scanned: usize, |
| 14 | + pub total_lines_processed: usize, |
| 15 | + pub total_matches_found: usize, |
| 16 | + pub scan_duration_ms: u64, |
| 17 | + pub cache_hits: usize, |
| 18 | + pub cache_misses: usize, |
| 19 | + pub simd_matches: usize, |
| 20 | + pub regex_matches: usize, |
| 21 | + pub file_read_time_ms: u64, |
| 22 | + pub pattern_search_time_ms: u64, |
| 23 | + pub result_processing_time_ms: u64, |
| 24 | + pub average_file_size_bytes: f64, |
| 25 | + pub cache_hit_rate: f64, |
| 26 | + pub throughput_files_per_second: f64, |
| 27 | + pub throughput_lines_per_second: f64, |
| 28 | +} |
| 29 | +``` |
| 30 | + |
| 31 | +### ScanMetrics (Internal) |
| 32 | + |
| 33 | +```rust |
| 34 | +struct ScanMetrics { |
| 35 | + files_processed: Arc<AtomicUsize>, |
| 36 | + lines_processed: Arc<AtomicUsize>, |
| 37 | + cache_hits: Arc<AtomicUsize>, |
| 38 | + cache_misses: Arc<AtomicUsize>, |
| 39 | + simd_matches: Arc<AtomicUsize>, |
| 40 | + regex_matches: Arc<AtomicUsize>, |
| 41 | + file_read_time: Arc<AtomicUsize>, |
| 42 | + pattern_search_time: Arc<AtomicUsize>, |
| 43 | + result_processing_time: Arc<AtomicUsize>, |
| 44 | +} |
| 45 | +``` |
| 46 | + |
| 47 | +## Scanner APIs |
| 48 | + |
| 49 | +### Standard Scanner |
| 50 | + |
| 51 | +```rust |
| 52 | +use code_guardian_core::Scanner; |
| 53 | + |
| 54 | +let scanner = Scanner::new(); |
| 55 | +let (matches, metrics) = scanner.scan_with_metrics(&path)?; |
| 56 | + |
| 57 | +// Basic metrics available |
| 58 | +println!("Files scanned: {}", metrics.total_files_scanned); |
| 59 | +println!("Duration: {}ms", metrics.scan_duration_ms); |
| 60 | +``` |
| 61 | + |
| 62 | +### Optimized Scanner |
| 63 | + |
| 64 | +```rust |
| 65 | +use code_guardian_core::OptimizedScanner; |
| 66 | + |
| 67 | +let scanner = OptimizedScanner::new(detectors); |
| 68 | +let (matches, metrics) = scanner.scan_optimized(&path)?; |
| 69 | + |
| 70 | +// Enhanced metrics with caching information |
| 71 | +println!("Cache hit rate: {:.2}%", metrics.cache_hit_rate); |
| 72 | +println!("Throughput: {:.1} files/sec", metrics.throughput_files_per_second); |
| 73 | +``` |
| 74 | + |
| 75 | +### Performance Optimized Scanner |
| 76 | + |
| 77 | +```rust |
| 78 | +use code_guardian_core::PerformanceOptimizedScanner; |
| 79 | + |
| 80 | +let scanner = PerformanceOptimizedScanner::new(detectors); |
| 81 | +let (matches, metrics) = scanner.scan_optimized(&path)?; |
| 82 | + |
| 83 | +// Advanced metrics with detailed timing |
| 84 | +println!("SIMD matches: {}", metrics.simd_matches); |
| 85 | +println!("Regex matches: {}", metrics.regex_matches); |
| 86 | +println!("File read time: {}ms", metrics.file_read_time_ms); |
| 87 | +println!("Pattern search time: {}ms", metrics.pattern_search_time_ms); |
| 88 | +``` |
| 89 | + |
| 90 | +## Metric Interpretation |
| 91 | + |
| 92 | +### Performance Indicators |
| 93 | + |
| 94 | +#### Throughput Metrics |
| 95 | +```rust |
| 96 | +// Files per second - overall scanning speed |
| 97 | +let files_per_sec = metrics.throughput_files_per_second; |
| 98 | + |
| 99 | +// Lines per second - content processing speed |
| 100 | +let lines_per_sec = metrics.throughput_lines_per_second; |
| 101 | + |
| 102 | +// Efficiency ratio |
| 103 | +let efficiency = lines_per_sec / files_per_sec; // Lines per file processed |
| 104 | +``` |
| 105 | + |
| 106 | +#### Cache Performance |
| 107 | +```rust |
| 108 | +// Cache effectiveness |
| 109 | +let cache_hit_rate = metrics.cache_hit_rate; |
| 110 | +if cache_hit_rate < 50.0 { |
| 111 | + println!("⚠️ Low cache hit rate - consider tuning cache size"); |
| 112 | +} else if cache_hit_rate > 90.0 { |
| 113 | + println!("✅ Excellent cache performance"); |
| 114 | +} |
| 115 | + |
| 116 | +// Cache utilization |
| 117 | +let total_cache_ops = metrics.cache_hits + metrics.cache_misses; |
| 118 | +let cache_utilization = total_cache_ops as f64 / metrics.total_files_scanned as f64; |
| 119 | +``` |
| 120 | + |
| 121 | +#### Detection Method Distribution |
| 122 | +```rust |
| 123 | +// Pattern detection breakdown |
| 124 | +let total_matches = metrics.simd_matches + metrics.regex_matches; |
| 125 | +let simd_percentage = (metrics.simd_matches as f64 / total_matches as f64) * 100.0; |
| 126 | + |
| 127 | +println!("SIMD detection: {:.1}%", simd_percentage); |
| 128 | +println!("Regex detection: {:.1}%", 100.0 - simd_percentage); |
| 129 | +``` |
| 130 | + |
| 131 | +#### Timing Analysis |
| 132 | +```rust |
| 133 | +// Time distribution analysis |
| 134 | +let total_processing_time = metrics.file_read_time_ms + |
| 135 | + metrics.pattern_search_time_ms + |
| 136 | + metrics.result_processing_time_ms; |
| 137 | + |
| 138 | +let read_percentage = (metrics.file_read_time_ms as f64 / total_processing_time as f64) * 100.0; |
| 139 | +let search_percentage = (metrics.pattern_search_time_ms as f64 / total_processing_time as f64) * 100.0; |
| 140 | +let process_percentage = (metrics.result_processing_time_ms as f64 / total_processing_time as f64) * 100.0; |
| 141 | + |
| 142 | +println!("Time breakdown:"); |
| 143 | +println!(" File reading: {:.1}%", read_percentage); |
| 144 | +println!(" Pattern search: {:.1}%", search_percentage); |
| 145 | +println!(" Result processing: {:.1}%", process_percentage); |
| 146 | +``` |
| 147 | + |
| 148 | +## Performance Monitoring |
| 149 | + |
| 150 | +### Real-time Monitoring |
| 151 | + |
| 152 | +```rust |
| 153 | +use code_guardian_core::PerformanceMonitor; |
| 154 | + |
| 155 | +let monitor = PerformanceMonitor::new(); |
| 156 | + |
| 157 | +// Record scan metrics |
| 158 | +monitor.record_scan(&metrics); |
| 159 | + |
| 160 | +// Get performance trends |
| 161 | +let avg_duration = monitor.average_scan_duration(); |
| 162 | +let trend = monitor.performance_trend(); |
| 163 | + |
| 164 | +match trend { |
| 165 | + PerformanceTrend::Improving => println!("📈 Performance improving"), |
| 166 | + PerformanceTrend::Degrading => println!("📉 Performance degrading"), |
| 167 | + PerformanceTrend::Stable => println!("📊 Performance stable"), |
| 168 | +} |
| 169 | +``` |
| 170 | + |
| 171 | +### Alerting Integration |
| 172 | + |
| 173 | +```rust |
| 174 | +use code_guardian_core::alerts::PerformanceAlert; |
| 175 | + |
| 176 | +let alert_config = PerformanceAlert::builder() |
| 177 | + .max_scan_duration_ms(30000) // 30 seconds |
| 178 | + .min_cache_hit_rate(0.7) // 70% |
| 179 | + .max_memory_usage_mb(1024) // 1GB |
| 180 | + .build(); |
| 181 | + |
| 182 | +if let Some(alert) = alert_config.check_metrics(&metrics) { |
| 183 | + println!("🚨 Performance Alert: {}", alert.message()); |
| 184 | + // Send to monitoring system |
| 185 | +} |
| 186 | +``` |
| 187 | + |
| 188 | +## Benchmark Integration |
| 189 | + |
| 190 | +### Custom Benchmarks |
| 191 | + |
| 192 | +```rust |
| 193 | +use criterion::{black_box, criterion_group, criterion_main, Criterion}; |
| 194 | +use code_guardian_core::*; |
| 195 | + |
| 196 | +fn benchmark_scanner_performance(c: &mut Criterion) { |
| 197 | + let test_data = create_test_data(); |
| 198 | + |
| 199 | + c.bench_function("optimized_scanner", |b| { |
| 200 | + let scanner = OptimizedScanner::new(create_detectors()); |
| 201 | + b.iter(|| { |
| 202 | + let (matches, metrics) = scanner.scan_optimized(black_box(&test_data)).unwrap(); |
| 203 | + black_box((matches, metrics)); |
| 204 | + }); |
| 205 | + }); |
| 206 | +} |
| 207 | + |
| 208 | +criterion_group!(benches, benchmark_scanner_performance); |
| 209 | +criterion_main!(benches); |
| 210 | +``` |
| 211 | + |
| 212 | +### Performance Regression Testing |
| 213 | + |
| 214 | +```rust |
| 215 | +#[test] |
| 216 | +fn test_performance_regression() { |
| 217 | + let scanner = OptimizedScanner::new(create_test_detectors()); |
| 218 | + let test_path = create_medium_test_data(); // 100 files, 500 lines each |
| 219 | + |
| 220 | + let start = std::time::Instant::now(); |
| 221 | + let (matches, metrics) = scanner.scan_optimized(&test_path).unwrap(); |
| 222 | + let duration = start.elapsed(); |
| 223 | + |
| 224 | + // Performance regression thresholds |
| 225 | + assert!(duration.as_millis() < 5000, "Scan took too long: {:?}", duration); |
| 226 | + assert!(metrics.cache_hit_rate > 0.5, "Cache hit rate too low: {}", metrics.cache_hit_rate); |
| 227 | + assert!(metrics.throughput_files_per_second > 20.0, "Throughput too low: {}", metrics.throughput_files_per_second); |
| 228 | +} |
| 229 | +``` |
| 230 | + |
| 231 | +## Configuration API |
| 232 | + |
| 233 | +### Scanner Configuration |
| 234 | + |
| 235 | +```rust |
| 236 | +use code_guardian_core::config::ScannerConfig; |
| 237 | + |
| 238 | +let config = ScannerConfig::builder() |
| 239 | + .batch_size(100) |
| 240 | + .parallel_workers(num_cpus::get()) |
| 241 | + .cache_size_mb(256) |
| 242 | + .adaptive_threshold(25) |
| 243 | + .enable_simd(true) |
| 244 | + .enable_metrics_collection(true) |
| 245 | + .build(); |
| 246 | + |
| 247 | +let scanner = PerformanceOptimizedScanner::with_config(detectors, config); |
| 248 | +``` |
| 249 | + |
| 250 | +### Metrics Configuration |
| 251 | + |
| 252 | +```rust |
| 253 | +use code_guardian_core::config::MetricsConfig; |
| 254 | + |
| 255 | +let metrics_config = MetricsConfig::builder() |
| 256 | + .collect_timing_details(true) |
| 257 | + .collect_cache_metrics(true) |
| 258 | + .collect_memory_metrics(true) |
| 259 | + .enable_real_time_monitoring(true) |
| 260 | + .build(); |
| 261 | + |
| 262 | +let scanner = scanner.with_metrics_config(metrics_config); |
| 263 | +``` |
| 264 | + |
| 265 | +## Export and Integration |
| 266 | + |
| 267 | +### JSON Export |
| 268 | + |
| 269 | +```rust |
| 270 | +// Export metrics as JSON |
| 271 | +let json = serde_json::to_string_pretty(&metrics)?; |
| 272 | +std::fs::write("scan_metrics.json", json)?; |
| 273 | +``` |
| 274 | + |
| 275 | +### Prometheus Integration |
| 276 | + |
| 277 | +```rust |
| 278 | +use code_guardian_core::metrics::PrometheusExporter; |
| 279 | + |
| 280 | +let exporter = PrometheusExporter::new(); |
| 281 | +exporter.export_metrics(&metrics, "code_guardian")?; |
| 282 | + |
| 283 | +// Metrics available at http://localhost:9090/metrics |
| 284 | +``` |
| 285 | + |
| 286 | +### CSV Export |
| 287 | + |
| 288 | +```rust |
| 289 | +use code_guardian_core::metrics::CsvExporter; |
| 290 | + |
| 291 | +let exporter = CsvExporter::new(); |
| 292 | +exporter.write_metrics(&metrics, "performance_log.csv")?; |
| 293 | +``` |
| 294 | + |
| 295 | +## Error Handling |
| 296 | + |
| 297 | +### Performance Errors |
| 298 | + |
| 299 | +```rust |
| 300 | +use code_guardian_core::errors::PerformanceError; |
| 301 | + |
| 302 | +match scanner.scan_optimized(&path) { |
| 303 | + Ok((matches, metrics)) => { |
| 304 | + // Success case |
| 305 | + }, |
| 306 | + Err(PerformanceError::TimeoutExceeded(duration)) => { |
| 307 | + println!("Scan timed out after {:?}", duration); |
| 308 | + }, |
| 309 | + Err(PerformanceError::MemoryLimitExceeded(usage)) => { |
| 310 | + println!("Memory limit exceeded: {} MB", usage); |
| 311 | + }, |
| 312 | + Err(PerformanceError::CacheCorruption) => { |
| 313 | + println!("Cache corruption detected, rebuilding..."); |
| 314 | + }, |
| 315 | + Err(e) => { |
| 316 | + println!("Performance error: {}", e); |
| 317 | + } |
| 318 | +} |
| 319 | +``` |
| 320 | + |
| 321 | +## Best Practices |
| 322 | + |
| 323 | +### Metrics Collection |
| 324 | +1. **Enable appropriate metrics** for your use case |
| 325 | +2. **Monitor trends** rather than individual data points |
| 326 | +3. **Set up alerting** for performance degradation |
| 327 | +4. **Export data** for analysis and reporting |
| 328 | + |
| 329 | +### Performance Optimization |
| 330 | +1. **Use cache hit rate** to tune cache sizes |
| 331 | +2. **Monitor timing breakdowns** to identify bottlenecks |
| 332 | +3. **Track throughput trends** to validate optimizations |
| 333 | +4. **Benchmark regularly** to catch regressions |
| 334 | + |
| 335 | +### Production Deployment |
| 336 | +1. **Configure appropriate thresholds** for your environment |
| 337 | +2. **Monitor memory usage** patterns over time |
| 338 | +3. **Set up automated performance testing** in CI/CD |
| 339 | +4. **Export metrics** to your monitoring infrastructure |
0 commit comments