aprender-cbtop 0.35.0

Compute Block Top - Real-time load testing and hardware monitoring TUI
Documentation
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
//! Types, structs, and data models for headless benchmark mode.

use crate::brick::BrickScore;
use serde::{Deserialize, Serialize};

/// Output format for benchmark results
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    Json,
    Text,
}

/// CPU frequency governor status (PERF-003)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuGovernorInfo {
    pub governor: String,
    pub is_performance: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_freq_mhz: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_freq_mhz: Option<u32>,
}

/// System information for benchmark context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInfo {
    pub cpu: String,
    pub cores: usize,
    pub memory_gb: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gpu: Option<String>,
    /// PERF-003: CPU governor status for deterministic benchmarks
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cpu_governor: Option<CpuGovernorInfo>,
}

impl SystemInfo {
    pub fn detect() -> Self {
        let cores = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1);

        // Try to get CPU info from /proc/cpuinfo on Linux
        let cpu = Self::detect_cpu();

        // Get memory info
        let memory_gb = Self::detect_memory_gb();

        // PERF-003: Detect CPU governor for deterministic benchmarks
        let cpu_governor = Self::detect_cpu_governor();

        Self {
            cpu,
            cores,
            memory_gb,
            gpu: None, // GPU detection requires CUDA/wgpu initialization
            cpu_governor,
        }
    }

    fn detect_cpu() -> String {
        #[cfg(target_os = "linux")]
        {
            if let Ok(content) = std::fs::read_to_string("/proc/cpuinfo") {
                for line in content.lines() {
                    if line.starts_with("model name") {
                        if let Some(name) = line.split(':').nth(1) {
                            return name.trim().to_string();
                        }
                    }
                }
            }
        }
        "Unknown CPU".to_string()
    }

    fn detect_memory_gb() -> u64 {
        #[cfg(target_os = "linux")]
        {
            if let Ok(content) = std::fs::read_to_string("/proc/meminfo") {
                for line in content.lines() {
                    if line.starts_with("MemTotal:") {
                        if let Some(kb_str) = line.split_whitespace().nth(1) {
                            if let Ok(kb) = kb_str.parse::<u64>() {
                                return kb / 1024 / 1024; // Convert KB to GB
                            }
                        }
                    }
                }
            }
        }
        0
    }

    /// PERF-003: Detect CPU frequency governor for deterministic benchmarks
    /// Warns if governor is not set to "performance" mode
    fn detect_cpu_governor() -> Option<CpuGovernorInfo> {
        #[cfg(target_os = "linux")]
        {
            // Read governor from first CPU core (cpu0)
            let governor_path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor";
            let cur_freq_path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq";
            let max_freq_path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq";

            if let Ok(governor) = std::fs::read_to_string(governor_path) {
                let governor = governor.trim().to_string();
                let is_performance = governor == "performance";

                let current_freq_mhz = std::fs::read_to_string(cur_freq_path)
                    .ok()
                    .and_then(|s| s.trim().parse::<u32>().ok())
                    .map(|khz| khz / 1000);

                let max_freq_mhz = std::fs::read_to_string(max_freq_path)
                    .ok()
                    .and_then(|s| s.trim().parse::<u32>().ok())
                    .map(|khz| khz / 1000);

                return Some(CpuGovernorInfo {
                    governor,
                    is_performance,
                    current_freq_mhz,
                    max_freq_mhz,
                });
            }
        }

        None
    }

    /// PERF-003: Check if CPU is in optimal state for benchmarking
    pub fn check_benchmark_readiness(&self) -> Vec<String> {
        let mut warnings = Vec::new();

        if let Some(ref gov) = self.cpu_governor {
            if !gov.is_performance {
                warnings.push(format!(
                    "CPU governor is '{}' (not 'performance'). For deterministic benchmarks, run: \
                     sudo cpupower frequency-set -g performance",
                    gov.governor
                ));
            }

            if let (Some(cur), Some(max)) = (gov.current_freq_mhz, gov.max_freq_mhz) {
                let ratio = cur as f64 / max as f64;
                if ratio < 0.9 {
                    warnings.push(format!(
                        "CPU running at {}MHz ({:.0}% of max {}MHz). Thermal throttling may affect results.",
                        cur, ratio * 100.0, max
                    ));
                }
            }
        }

        warnings
    }
}

/// Benchmark configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkConfig {
    pub backend: String,
    pub workload: String,
    pub size: usize,
    pub iterations: u64,
}

/// Latency statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LatencyStats {
    pub mean: f64,
    pub min: f64,
    pub max: f64,
    pub p50: f64,
    pub p95: f64,
    pub p99: f64,
    pub cv_percent: f64,
}

/// Score breakdown
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScoreInfo {
    pub total: u8,
    pub grade: String,
    pub performance: u8,
    pub efficiency: u8,
    pub correctness: u8,
    pub stability: u8,
}

impl From<BrickScore> for ScoreInfo {
    fn from(score: BrickScore) -> Self {
        Self {
            total: score.total(),
            grade: format!("{:?}", score.grade()),
            performance: score.performance,
            efficiency: score.efficiency,
            correctness: score.correctness,
            stability: score.stability,
        }
    }
}

/// Benchmark results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkResult {
    pub version: String,
    pub timestamp: String,
    pub duration_secs: f64,
    pub system: SystemInfo,
    pub benchmark: BenchmarkConfig,
    pub results: BenchmarkResults,
    pub score: ScoreInfo,
    /// PERF-003: Warnings about benchmark environment
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

/// Core benchmark results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkResults {
    pub gflops: f64,
    pub throughput_ops_sec: f64,
    pub latency_ms: LatencyStats,
}

impl BenchmarkResult {
    /// Format result for output
    pub fn format(&self, format: OutputFormat) -> String {
        match format {
            OutputFormat::Json => {
                serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
            }
            OutputFormat::Text => self.format_text(),
        }
    }

    fn format_text(&self) -> String {
        format!(
            r#"
=== cbtop Benchmark Results ===

System:
  CPU: {}
  Cores: {}
  Memory: {} GB

Benchmark:
  Backend: {}
  Workload: {}
  Size: {} elements
  Iterations: {}
  Duration: {:.2}s

Results:
  GFLOP/s: {:.2}
  Throughput: {:.0} ops/sec
  Latency (ms):
    Mean: {:.3}
    P50:  {:.3}
    P95:  {:.3}
    P99:  {:.3}
    CV:   {:.1}%

Score: {}/100 (Grade: {})
  Performance:  {}/40
  Efficiency:   {}/25
  Correctness:  {}/20
  Stability:    {}/15
{}
"#,
            self.system.cpu,
            self.system.cores,
            self.system.memory_gb,
            self.benchmark.backend,
            self.benchmark.workload,
            self.benchmark.size,
            self.benchmark.iterations,
            self.duration_secs,
            self.results.gflops,
            self.results.throughput_ops_sec,
            self.results.latency_ms.mean,
            self.results.latency_ms.p50,
            self.results.latency_ms.p95,
            self.results.latency_ms.p99,
            self.results.latency_ms.cv_percent,
            self.score.total,
            self.score.grade,
            self.score.performance,
            self.score.efficiency,
            self.score.correctness,
            self.score.stability,
            // PERF-003: Show warnings if any
            if self.warnings.is_empty() {
                String::new()
            } else {
                format!(
                    "\nWarnings:\n{}",
                    self.warnings
                        .iter()
                        .map(|w| format!("  - {}", w))
                        .collect::<Vec<_>>()
                        .join("\n")
                )
            },
        )
    }

    /// Check for regression against baseline
    pub fn check_regression(&self, baseline: &BenchmarkResult, threshold: f64) -> RegressionResult {
        let change_percent =
            (self.results.gflops - baseline.results.gflops) / baseline.results.gflops * 100.0;

        RegressionResult {
            baseline_gflops: baseline.results.gflops,
            current_gflops: self.results.gflops,
            change_percent,
            threshold_percent: threshold,
            is_regression: change_percent < -threshold,
            status: if change_percent < -threshold {
                "REGRESSION".to_string()
            } else if change_percent > threshold {
                "IMPROVEMENT".to_string()
            } else {
                "STABLE".to_string()
            },
        }
    }

    /// Compare multiple benchmark results
    pub fn compare(results: &[(String, BenchmarkResult)]) -> ComparisonResult {
        let comparisons: Vec<_> = results
            .iter()
            .map(|(name, r)| BackendComparison {
                backend: name.clone(),
                gflops: r.results.gflops,
                score: r.score.total,
                latency_mean_ms: r.results.latency_ms.mean,
            })
            .collect();

        let best = comparisons
            .iter()
            .max_by(|a, b| {
                a.gflops
                    .partial_cmp(&b.gflops)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|c| c.backend.clone())
            .unwrap_or_default();

        ComparisonResult {
            backends: comparisons,
            recommended: best,
        }
    }
}

/// Regression check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegressionResult {
    pub baseline_gflops: f64,
    pub current_gflops: f64,
    pub change_percent: f64,
    pub threshold_percent: f64,
    pub is_regression: bool,
    pub status: String,
}

impl RegressionResult {
    pub fn format(&self, format: OutputFormat) -> String {
        match format {
            OutputFormat::Json => {
                serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
            }
            OutputFormat::Text => {
                format!(
                    r#"
=== Regression Check ===

Baseline: {:.2} GFLOP/s
Current:  {:.2} GFLOP/s
Change:   {:+.1}%
Threshold: {:.1}%

Status: {}
"#,
                    self.baseline_gflops,
                    self.current_gflops,
                    self.change_percent,
                    self.threshold_percent,
                    self.status,
                )
            }
        }
    }
}

/// Backend comparison for --compare mode
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackendComparison {
    pub backend: String,
    pub gflops: f64,
    pub score: u8,
    pub latency_mean_ms: f64,
}

/// Comparison result for multiple backends
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComparisonResult {
    pub backends: Vec<BackendComparison>,
    pub recommended: String,
}

impl ComparisonResult {
    pub fn format(&self, format: OutputFormat) -> String {
        match format {
            OutputFormat::Json => {
                serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
            }
            OutputFormat::Text => {
                let mut s = String::from("\n=== Backend Comparison ===\n\n");
                s.push_str("Backend      GFLOP/s   Score   Latency\n");
                s.push_str("----------------------------------------\n");
                for c in &self.backends {
                    s.push_str(&format!(
                        "{:<12} {:>7.2}   {:>3}     {:.3}ms\n",
                        c.backend, c.gflops, c.score, c.latency_mean_ms
                    ));
                }
                s.push_str(&format!("\nRecommended: {}\n", self.recommended));
                s
            }
        }
    }
}