-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathregression_analysis_comprehensive.rs
More file actions
507 lines (423 loc) · 20.3 KB
/
regression_analysis_comprehensive.rs
File metadata and controls
507 lines (423 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Comprehensive Regression Analysis Examples
//!
//! This example demonstrates EVERY aspect of the new Regression Analysis system :
//! - `RegressionAnalyzer` with all baseline strategies (Fixed, Rolling Average, Previous Run)
//! - `HistoricalResults` management and `TimestampedResults` creation
//! - Performance trend detection (Improving, Degrading, Stable)
//! - Statistical significance testing with configurable thresholds
//! - Professional markdown report generation with regression insights
//! - Integration with `PerformanceReport` templates
//! - Real-world scenarios: code optimization, library upgrades, performance monitoring
#![ cfg( feature = "enabled" ) ]
#![ cfg( feature = "markdown_reports" ) ]
#![ allow( clippy ::uninlined_format_args ) ]
#![ allow( clippy ::format_push_string ) ]
#![ allow( clippy ::cast_lossless ) ]
#![ allow( clippy ::cast_possible_truncation ) ]
#![ allow( clippy ::cast_precision_loss ) ]
#![ allow( clippy ::std_instead_of_core ) ]
#![ allow( clippy ::needless_raw_string_hashes ) ]
#![ allow( clippy ::too_many_lines ) ]
use benchkit ::prelude :: *;
use std ::collections ::HashMap;
use std ::time :: { Duration, SystemTime };
/// Create current benchmark results showing performance improvements
fn create_current_results() -> HashMap< String, BenchmarkResult >
{
let mut results = HashMap ::new();
// Fast sort algorithm - recently optimized, showing improvement
let fast_sort_times = vec![
Duration ::from_micros( 85 ), Duration ::from_micros( 88 ), Duration ::from_micros( 82 ),
Duration ::from_micros( 87 ), Duration ::from_micros( 84 ), Duration ::from_micros( 86 ),
Duration ::from_micros( 89 ), Duration ::from_micros( 81 ), Duration ::from_micros( 88 ),
Duration ::from_micros( 85 ), Duration ::from_micros( 87 ), Duration ::from_micros( 83 ),
Duration ::from_micros( 86 ), Duration ::from_micros( 84 ), Duration ::from_micros( 88 )
];
results.insert( "fast_sort".to_string(), BenchmarkResult ::new( "fast_sort", fast_sort_times ) );
// Hash function - stable performance
let hash_times = vec![
Duration ::from_nanos( 150 ), Duration ::from_nanos( 152 ), Duration ::from_nanos( 148 ),
Duration ::from_nanos( 151 ), Duration ::from_nanos( 149 ), Duration ::from_nanos( 150 ),
Duration ::from_nanos( 153 ), Duration ::from_nanos( 147 ), Duration ::from_nanos( 151 ),
Duration ::from_nanos( 150 ), Duration ::from_nanos( 152 ), Duration ::from_nanos( 149 )
];
results.insert( "hash_function".to_string(), BenchmarkResult ::new( "hash_function", hash_times ) );
// Memory allocator - performance regression after system update
let allocator_times = vec![
Duration ::from_micros( 320 ), Duration ::from_micros( 335 ), Duration ::from_micros( 315 ),
Duration ::from_micros( 330 ), Duration ::from_micros( 325 ), Duration ::from_micros( 340 ),
Duration ::from_micros( 310 ), Duration ::from_micros( 345 ), Duration ::from_micros( 318 ),
Duration ::from_micros( 332 ), Duration ::from_micros( 327 ), Duration ::from_micros( 338 )
];
results.insert( "memory_allocator".to_string(), BenchmarkResult ::new( "memory_allocator", allocator_times ) );
results
}
/// Create historical baseline data for fixed baseline strategy
fn create_baseline_historical_data() -> HistoricalResults
{
let mut baseline_data = HashMap ::new();
// Baseline: fast_sort before optimization (slower performance)
let baseline_fast_sort = vec![
Duration ::from_micros( 110 ), Duration ::from_micros( 115 ), Duration ::from_micros( 108 ),
Duration ::from_micros( 112 ), Duration ::from_micros( 117 ), Duration ::from_micros( 111 ),
Duration ::from_micros( 114 ), Duration ::from_micros( 107 ), Duration ::from_micros( 113 ),
Duration ::from_micros( 109 ), Duration ::from_micros( 116 ), Duration ::from_micros( 106 )
];
baseline_data.insert( "fast_sort".to_string(), BenchmarkResult ::new( "fast_sort", baseline_fast_sort ) );
// Baseline: hash_function (similar performance)
let baseline_hash = vec![
Duration ::from_nanos( 148 ), Duration ::from_nanos( 152 ), Duration ::from_nanos( 146 ),
Duration ::from_nanos( 150 ), Duration ::from_nanos( 154 ), Duration ::from_nanos( 147 ),
Duration ::from_nanos( 151 ), Duration ::from_nanos( 149 ), Duration ::from_nanos( 153 ),
Duration ::from_nanos( 148 ), Duration ::from_nanos( 152 ), Duration ::from_nanos( 150 )
];
baseline_data.insert( "hash_function".to_string(), BenchmarkResult ::new( "hash_function", baseline_hash ) );
// Baseline: memory_allocator before system update (better performance)
let baseline_allocator = vec![
Duration ::from_micros( 280 ), Duration ::from_micros( 285 ), Duration ::from_micros( 275 ),
Duration ::from_micros( 282 ), Duration ::from_micros( 287 ), Duration ::from_micros( 278 ),
Duration ::from_micros( 284 ), Duration ::from_micros( 276 ), Duration ::from_micros( 283 ),
Duration ::from_micros( 279 ), Duration ::from_micros( 286 ), Duration ::from_micros( 277 )
];
baseline_data.insert( "memory_allocator".to_string(), BenchmarkResult ::new( "memory_allocator", baseline_allocator ) );
HistoricalResults ::new().with_baseline( baseline_data )
}
/// Create historical runs for rolling average strategy
fn create_rolling_average_historical_data() -> HistoricalResults
{
let mut historical_runs = Vec ::new();
// Historical run 1 : 2 weeks ago
let mut run1_results = HashMap ::new();
let run1_fast_sort = vec![ Duration ::from_micros( 120 ), Duration ::from_micros( 125 ), Duration ::from_micros( 118 ) ];
let run1_hash = vec![ Duration ::from_nanos( 155 ), Duration ::from_nanos( 160 ), Duration ::from_nanos( 150 ) ];
let run1_allocator = vec![ Duration ::from_micros( 290 ), Duration ::from_micros( 295 ), Duration ::from_micros( 285 ) ];
run1_results.insert( "fast_sort".to_string(), BenchmarkResult ::new( "fast_sort", run1_fast_sort ) );
run1_results.insert( "hash_function".to_string(), BenchmarkResult ::new( "hash_function", run1_hash ) );
run1_results.insert( "memory_allocator".to_string(), BenchmarkResult ::new( "memory_allocator", run1_allocator ) );
historical_runs.push( TimestampedResults ::new(
SystemTime ::now() - Duration ::from_secs( 1_209_600 ), // 2 weeks ago
run1_results
) );
// Historical run 2 : 1 week ago
let mut run2_results = HashMap ::new();
let run2_fast_sort = vec![ Duration ::from_micros( 100 ), Duration ::from_micros( 105 ), Duration ::from_micros( 98 ) ];
let run2_hash = vec![ Duration ::from_nanos( 150 ), Duration ::from_nanos( 155 ), Duration ::from_nanos( 145 ) ];
let run2_allocator = vec![ Duration ::from_micros( 285 ), Duration ::from_micros( 290 ), Duration ::from_micros( 280 ) ];
run2_results.insert( "fast_sort".to_string(), BenchmarkResult ::new( "fast_sort", run2_fast_sort ) );
run2_results.insert( "hash_function".to_string(), BenchmarkResult ::new( "hash_function", run2_hash ) );
run2_results.insert( "memory_allocator".to_string(), BenchmarkResult ::new( "memory_allocator", run2_allocator ) );
historical_runs.push( TimestampedResults ::new(
SystemTime ::now() - Duration ::from_secs( 604_800 ), // 1 week ago
run2_results
) );
// Historical run 3 : 3 days ago
let mut run3_results = HashMap ::new();
let run3_fast_sort = vec![ Duration ::from_micros( 95 ), Duration ::from_micros( 98 ), Duration ::from_micros( 92 ) ];
let run3_hash = vec![ Duration ::from_nanos( 148 ), Duration ::from_nanos( 153 ), Duration ::from_nanos( 147 ) ];
let run3_allocator = vec![ Duration ::from_micros( 305 ), Duration ::from_micros( 310 ), Duration ::from_micros( 300 ) ];
run3_results.insert( "fast_sort".to_string(), BenchmarkResult ::new( "fast_sort", run3_fast_sort ) );
run3_results.insert( "hash_function".to_string(), BenchmarkResult ::new( "hash_function", run3_hash ) );
run3_results.insert( "memory_allocator".to_string(), BenchmarkResult ::new( "memory_allocator", run3_allocator ) );
historical_runs.push( TimestampedResults ::new(
SystemTime ::now() - Duration ::from_secs( 259_200 ), // 3 days ago
run3_results
) );
HistoricalResults ::new().with_historical_runs( historical_runs )
}
/// Create previous run data for previous run strategy
fn create_previous_run_historical_data() -> HistoricalResults
{
let mut previous_results = HashMap ::new();
// Previous run: yesterday's results
let prev_fast_sort = vec![ Duration ::from_micros( 90 ), Duration ::from_micros( 95 ), Duration ::from_micros( 88 ) ];
let prev_hash = vec![ Duration ::from_nanos( 149 ), Duration ::from_nanos( 154 ), Duration ::from_nanos( 146 ) ];
let prev_allocator = vec![ Duration ::from_micros( 295 ), Duration ::from_micros( 300 ), Duration ::from_micros( 290 ) ];
previous_results.insert( "fast_sort".to_string(), BenchmarkResult ::new( "fast_sort", prev_fast_sort ) );
previous_results.insert( "hash_function".to_string(), BenchmarkResult ::new( "hash_function", prev_hash ) );
previous_results.insert( "memory_allocator".to_string(), BenchmarkResult ::new( "memory_allocator", prev_allocator ) );
let previous_run = TimestampedResults ::new(
SystemTime ::now() - Duration ::from_secs( 86_400 ), // 1 day ago
previous_results
);
HistoricalResults ::new().with_previous_run( previous_run )
}
/// Demonstrate Fixed Baseline Strategy
fn demonstrate_fixed_baseline_strategy()
{
println!( "🎯 FIXED BASELINE STRATEGY DEMONSTRATION" );
println!( "=========================================" );
println!( "Comparing current performance against a fixed baseline measurement." );
println!( "Use case: Long-term performance tracking against a stable reference point.\n" );
let current_results = create_current_results();
let historical = create_baseline_historical_data();
// Create analyzer with strict significance threshold
let analyzer = RegressionAnalyzer ::new()
.with_baseline_strategy( BaselineStrategy ::FixedBaseline )
.with_significance_threshold( 0.01 ) // 1% significance level (very strict)
.with_trend_window( 5 );
let regression_report = analyzer.analyze( ¤t_results, &historical );
// Display analysis results
println!( "📊 REGRESSION ANALYSIS RESULTS: " );
println!( "--------------------------------" );
for operation in [ "fast_sort", "hash_function", "memory_allocator" ]
{
if let Some( trend ) = regression_report.get_trend_for( operation )
{
let significance = if regression_report.is_statistically_significant( operation )
{
"✓ Statistically Significant"
}
else
{
"- Not Significant"
};
let trend_emoji = match trend
{
PerformanceTrend ::Improving => "🟢 IMPROVING",
PerformanceTrend ::Degrading => "🔴 DEGRADING",
PerformanceTrend ::Stable => "🟡 STABLE",
};
println!( " {} - {} ({})", operation, trend_emoji, significance );
}
}
// Generate markdown report
let markdown_report = regression_report.format_markdown();
println!( "\n📝 GENERATED MARKDOWN REPORT: " );
println!( "------------------------------" );
println!( "{}", markdown_report );
println!( "\n" );
}
/// Demonstrate Rolling Average Strategy
fn demonstrate_rolling_average_strategy()
{
println!( "📈 ROLLING AVERAGE STRATEGY DEMONSTRATION" );
println!( "==========================================" );
println!( "Comparing current performance against rolling average of recent runs." );
println!( "Use case: Detecting gradual performance trends over time.\n" );
let current_results = create_current_results();
let historical = create_rolling_average_historical_data();
// Create analyzer optimized for trend detection
let analyzer = RegressionAnalyzer ::new()
.with_baseline_strategy( BaselineStrategy ::RollingAverage )
.with_significance_threshold( 0.05 ) // 5% significance level (moderate)
.with_trend_window( 3 ); // Look at last 3 runs for trend analysis
let regression_report = analyzer.analyze( ¤t_results, &historical );
// Display comprehensive analysis
println!( "📊 TREND ANALYSIS RESULTS: " );
println!( "--------------------------" );
for operation in [ "fast_sort", "hash_function", "memory_allocator" ]
{
if regression_report.has_historical_data( operation )
{
let trend = regression_report.get_trend_for( operation ).unwrap();
let significance = regression_report.is_statistically_significant( operation );
println!( " 🔍 {} Analysis: ", operation );
println!( " Trend: {:?}", trend );
println!( " Statistical Significance: {}", if significance { "Yes" } else { "No" } );
println!( " Historical Data Points: Available" );
println!();
}
}
// Check overall report status
if regression_report.has_significant_changes()
{
println!( "⚠️ ALERT: Significant performance changes detected!" );
}
else
{
println!( "✅ STATUS: Performance within normal variation ranges" );
}
println!( "\n" );
}
/// Demonstrate Previous Run Strategy
fn demonstrate_previous_run_strategy()
{
println!( "⏮️ PREVIOUS RUN STRATEGY DEMONSTRATION" );
println!( "=======================================" );
println!( "Comparing current performance against the immediate previous run." );
println!( "Use case: Detecting immediate impact of recent changes.\n" );
let current_results = create_current_results();
let historical = create_previous_run_historical_data();
// Create analyzer for immediate change detection
let analyzer = RegressionAnalyzer ::new()
.with_baseline_strategy( BaselineStrategy ::PreviousRun )
.with_significance_threshold( 0.10 ) // 10% significance level (lenient)
.with_trend_window( 2 ); // Only compare current vs previous
let regression_report = analyzer.analyze( ¤t_results, &historical );
// Display immediate change analysis
println!( "📊 IMMEDIATE CHANGE ANALYSIS: " );
println!( "-----------------------------" );
if regression_report.has_previous_run_data()
{
for operation in [ "fast_sort", "hash_function", "memory_allocator" ]
{
if let Some( trend ) = regression_report.get_trend_for( operation )
{
let change_indicator = match trend
{
PerformanceTrend ::Improving => "↗️ Performance improved since last run",
PerformanceTrend ::Degrading => "↘️ Performance degraded since last run",
PerformanceTrend ::Stable => "➡️ Performance stable since last run",
};
println!( " {} - {}", operation, change_indicator );
}
}
}
else
{
println!( " ❌ No previous run data available for comparison" );
}
println!( "\n" );
}
/// Demonstrate comprehensive template integration
fn demonstrate_template_integration()
{
println!( "📋 PERFORMANCE REPORT TEMPLATE INTEGRATION" );
println!( "===========================================" );
println!( "Demonstrating full integration with PerformanceReport templates." );
println!( "Use case: Automated performance documentation with regression insights.\n" );
let current_results = create_current_results();
let historical = create_rolling_average_historical_data();
// Create comprehensive performance report with regression analysis
let template = PerformanceReport ::new()
.title( "Algorithm Performance Analysis with Regression Detection" )
.add_context( "Comprehensive analysis after code optimization and system updates" )
.include_statistical_analysis( true )
.include_regression_analysis( true )
.with_historical_data( historical )
.add_custom_section( CustomSection ::new(
"Optimization Impact Analysis",
r#"### Key Changes Made
- **fast_sort** : Applied cache-friendly memory access patterns
- **hash_function** : No changes (stable baseline)
- **memory_allocator** : System update may have introduced overhead
### Expected Outcomes
- fast_sort should show significant improvement
- hash_function should remain stable
- memory_allocator performance needs investigation"#
) );
match template.generate( ¤t_results )
{
Ok( report ) =>
{
println!( "✅ GENERATED COMPREHENSIVE PERFORMANCE REPORT: " );
println!( "----------------------------------------------" );
// Display key sections
let lines: Vec< &str > = report.lines().collect();
let mut in_regression_section = false;
let mut regression_lines = Vec ::new();
for line in lines
{
if line.contains( "## Regression Analysis" )
{
in_regression_section = true;
}
else if line.starts_with( "## " ) && in_regression_section
{
break;
}
if in_regression_section
{
regression_lines.push( line );
}
}
if !regression_lines.is_empty()
{
println!( "📊 REGRESSION ANALYSIS SECTION: " );
for line in regression_lines.iter().take( 15 ) // Show first 15 lines
{
println!( "{}", line );
}
if regression_lines.len() > 15
{
println!( "... ({} more lines)", regression_lines.len() - 15 );
}
}
// Report statistics
let report_size = report.len();
let line_count = report.matches( '\n' ).count();
println!( "\n📈 REPORT STATISTICS: " );
println!( " Size: {} characters", report_size );
println!( " Lines: {} lines", line_count );
println!( " Includes: Executive Summary, Performance Results, Statistical Analysis, Regression Analysis, Custom Sections" );
},
Err( e ) =>
{
println!( "❌ ERROR generating report: {}", e );
}
}
println!( "\n" );
}
/// Demonstrate statistical significance tuning
fn demonstrate_significance_tuning()
{
println!( "🎛️ STATISTICAL SIGNIFICANCE TUNING" );
println!( "===================================" );
println!( "Demonstrating how different significance thresholds affect regression detection." );
println!( "Use case: Calibrating sensitivity for different environments.\n" );
let current_results = create_current_results();
let historical = create_baseline_historical_data();
let thresholds = vec![ 0.01, 0.05, 0.10, 0.20 ];
for &threshold in &thresholds
{
println!( "📊 ANALYSIS WITH {}% SIGNIFICANCE THRESHOLD: ", ( threshold * 100.0 ) as i32 );
let analyzer = RegressionAnalyzer ::new()
.with_baseline_strategy( BaselineStrategy ::FixedBaseline )
.with_significance_threshold( threshold );
let regression_report = analyzer.analyze( ¤t_results, &historical );
let mut significant_count = 0;
let operations = [ "fast_sort", "hash_function", "memory_allocator" ];
for operation in &operations
{
if regression_report.is_statistically_significant( operation )
{
significant_count += 1;
}
}
println!( " Significant changes detected: {}/{}", significant_count, operations.len() );
// Show specific results for fast_sort (known improvement)
if regression_report.is_statistically_significant( "fast_sort" )
{
println!( " fast_sort: ✓ Significant improvement detected" );
}
else
{
println!( " fast_sort: - Improvement not statistically significant at this level" );
}
println!();
}
println!( "💡 TUNING GUIDANCE: " );
println!( " - Strict thresholds (1-5%) : Production environments, critical systems" );
println!( " - Moderate thresholds (5-10%) : Development, performance monitoring" );
println!( " - Lenient thresholds (10-20%) : Early development, noisy environments\n" );
}
/// Main demonstration function
fn main()
{
println!( "🚀 BENCHKIT REGRESSION ANALYSIS COMPREHENSIVE DEMO" );
println!( "====================================================" );
println!( "This example demonstrates every aspect of the new regression analysis system: \n" );
// Core strategy demonstrations
demonstrate_fixed_baseline_strategy();
demonstrate_rolling_average_strategy();
demonstrate_previous_run_strategy();
// Advanced features
demonstrate_template_integration();
demonstrate_significance_tuning();
println!( "✨ SUMMARY OF DEMONSTRATED FEATURES: " );
println!( "=====================================" );
println!( "✅ All three baseline strategies (Fixed, Rolling Average, Previous Run)" );
println!( "✅ Performance trend detection (Improving, Degrading, Stable)" );
println!( "✅ Statistical significance testing with configurable thresholds" );
println!( "✅ Historical data management (baseline, runs, previous run)" );
println!( "✅ Professional markdown report generation" );
println!( "✅ Full PerformanceReport template integration" );
println!( "✅ Real-world use cases and configuration guidance" );
println!( "\n🎯 Ready for production use in performance monitoring workflows!" );
}
#[ cfg( not( feature = "enabled" ) ) ]
fn main()
{
println!( "This example requires the 'enabled' feature." );
println!( "Run with: cargo run --example regression_analysis_comprehensive --features enabled" );
}