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
//! Benchmark command implementation
//!
//! Provides comprehensive benchmarking functionality including:
//! - Google Benchmark execution
//! - Result storage and comparison
//! - Regression detection
//! - CI integration
use std::path::{Path, PathBuf};
use anyhow::Result;
use clap::Args;
use crate::builder::platforms::benches::BenchesBuilder;
use crate::builder::{BuildContext, BuildOptions, PlatformBuilder};
use crate::commands::build::{BuildTarget, LinkType, WindowsToolchain};
use crate::config::CcgoConfig;
use crate::testing::benchmark::{BenchmarkStore, ComparisonReport};
use crate::testing::ci::{CiFormat, CiReporter};
/// Run Google Benchmark benchmarks
#[derive(Args, Debug)]
pub struct BenchCommand {
/// Benchmark filter pattern (e.g., "BM_Sort*")
#[arg(long)]
pub filter: Option<String>,
/// Generate IDE project for benchmarks instead of running
#[arg(long)]
pub ide_project: bool,
/// Build benchmarks without running them
#[arg(long)]
pub build_only: bool,
/// Run benchmarks without building (assumes already built)
#[arg(long)]
pub run_only: bool,
/// Number of parallel jobs for building
#[arg(short, long)]
pub jobs: Option<usize>,
/// Build in release mode (recommended for benchmarks)
#[arg(long, default_value = "true")]
pub release: bool,
/// Named build profile (`[profile.<name>]` in CCGO.toml); composes with mode and sanitizer.
/// The names `debug` and `release` are reserved — use the mode flags instead.
#[arg(long)]
pub profile: Option<String>,
/// Save results with this identifier (e.g., git commit hash)
#[arg(long)]
pub save: Option<String>,
/// Compare results with a baseline run
#[arg(long)]
pub baseline: Option<String>,
/// Compare with the latest saved run
#[arg(long)]
pub compare_latest: bool,
/// Regression threshold percentage (default: 5%)
#[arg(long, default_value = "5.0")]
pub threshold: f64,
/// Fail if regressions are detected
#[arg(long)]
pub fail_on_regression: bool,
/// Output format for CI integration
#[arg(long)]
pub ci_format: Option<String>,
/// List all saved benchmark runs
#[arg(long)]
pub list_runs: bool,
/// Export comparison as Markdown
#[arg(long)]
pub export_markdown: Option<PathBuf>,
/// Export comparison as JSON
#[arg(long)]
pub export_json: Option<PathBuf>,
/// Enable AddressSanitizer (ASan). Composes with `--debug`/`--release` and `--profile`.
/// Output: `ccgo_build/{mode}[-{profile}]-asan/`. Mutually exclusive with `--tsan`.
#[arg(long, conflicts_with = "tsan")]
pub asan: bool,
/// Enable ThreadSanitizer (TSan). Composes with `--debug`/`--release` and `--profile`.
/// Output: `ccgo_build/{mode}[-{profile}]-tsan/`. Mutually exclusive with `--asan`.
#[arg(long, conflicts_with = "asan")]
pub tsan: bool,
}
impl BenchCommand {
/// Execute the bench command
pub fn execute(self, verbose: bool) -> Result<()> {
// Handle list runs
if self.list_runs {
return self.list_saved_runs();
}
// Load project configuration
let config = CcgoConfig::load()?;
let project_root = std::env::current_dir()?;
let sanitizer = if self.asan {
Some(crate::builder::sanitizer::SanitizerKind::Address)
} else if self.tsan {
Some(crate::builder::sanitizer::SanitizerKind::Thread)
} else {
None
};
// Validate reserved profile names.
if let Some(ref pname) = self.profile {
if matches!(pname.as_str(), "debug" | "release") {
anyhow::bail!("'--profile {pname}' is reserved; use --debug or --release instead");
}
}
let release = self.release; // mode is CLI-only; profile.release is never applied
let profile_name = self.profile.clone();
// Create build context for benchmarks
let options = BuildOptions {
target: BuildTarget::Linux, // Placeholder, not used by benchmarks
architectures: vec![],
link_type: LinkType::Both,
use_docker: false,
auto_docker: false,
jobs: self.jobs,
ide_project: self.ide_project,
release,
native_only: false,
toolchain: WindowsToolchain::Auto,
verbose,
dev: false,
features: vec![],
use_default_features: true,
all_features: false,
cache: Some("auto".to_string()),
analytics: false,
linkage_default: None,
linkage_overrides: std::collections::HashMap::new(),
sanitizer,
profile_name,
..BuildOptions::default()
};
let ctx = BuildContext::new(project_root.clone(), config, options);
let builder = BenchesBuilder::new();
// Use the build directory from the build context (respects config and profile).
let build_dir = ctx.cmake_build_dir.clone();
if self.ide_project {
// Generate IDE project
return builder.generate_ide_project(&ctx);
}
// Build benchmarks if needed
if !self.run_only {
if verbose {
eprintln!("Building benchmarks...");
}
builder.build(&ctx)?;
}
// Run benchmarks if needed
if !self.build_only {
if verbose {
eprintln!("Running benchmarks...");
}
builder.run_benchmarks(&ctx, self.filter.as_deref())?;
// Handle result storage and comparison
self.process_results(&project_root, &build_dir, verbose)?;
}
Ok(())
}
/// List saved benchmark runs
fn list_saved_runs(&self) -> Result<()> {
let store = BenchmarkStore::new(BenchmarkStore::default_path());
let runs = store.list()?;
if runs.is_empty() {
println!("No saved benchmark runs found.");
println!("Use --save <id> to save benchmark results.");
} else {
println!("Saved benchmark runs:");
for run_id in runs {
println!(" - {}", run_id);
}
}
Ok(())
}
/// Process benchmark results (save, compare, report)
fn process_results(&self, project_root: &Path, build_dir: &Path, verbose: bool) -> Result<()> {
let store = BenchmarkStore::new(project_root.join(".ccgo").join("benchmarks"));
// Find the latest benchmark JSON output
let json_file = self.find_benchmark_json(build_dir)?;
if let Some(json_path) = json_file {
// Parse the results
let mut current_run = store.parse_gbench_json(&json_path)?;
// Set run ID
if let Some(ref save_id) = self.save {
current_run.run_id = save_id.clone();
} else {
// Use timestamp as default ID
current_run.run_id = chrono::Local::now().format("%Y%m%d_%H%M%S").to_string();
}
// Save if requested
if self.save.is_some() {
let saved_path = store.save(¤t_run)?;
eprintln!("📁 Benchmark results saved: {}", saved_path.display());
}
// Compare with baseline
let comparison = if let Some(ref baseline_id) = self.baseline {
Some(self.compare_with_baseline(&store, baseline_id, ¤t_run)?)
} else if self.compare_latest {
match store.load_latest() {
Ok(baseline) => {
if baseline.run_id != current_run.run_id {
Some(ComparisonReport::new(
&baseline,
¤t_run,
self.threshold,
))
} else {
None
}
}
Err(_) => None,
}
} else {
None
};
// Process comparison
if let Some(report) = comparison {
self.report_comparison(&report, verbose)?;
}
} else if verbose {
eprintln!(
"Warning: No benchmark JSON output found in {}",
build_dir.display()
);
}
Ok(())
}
/// Find benchmark JSON output file
fn find_benchmark_json(&self, build_dir: &Path) -> Result<Option<PathBuf>> {
if !build_dir.exists() {
return Ok(None);
}
let mut latest: Option<(PathBuf, std::time::SystemTime)> = None;
for entry in std::fs::read_dir(build_dir)? {
let entry = entry?;
let path = entry.path();
if path.is_file() {
let name = path.file_name().unwrap().to_string_lossy();
if name.contains("_result") && name.ends_with(".json") {
if let Ok(metadata) = path.metadata() {
if let Ok(modified) = metadata.modified() {
match &latest {
None => latest = Some((path, modified)),
Some((_, latest_time)) if modified > *latest_time => {
latest = Some((path, modified))
}
_ => {}
}
}
}
}
}
}
Ok(latest.map(|(p, _)| p))
}
/// Compare with a baseline run
fn compare_with_baseline(
&self,
store: &BenchmarkStore,
baseline_id: &str,
current: &crate::testing::benchmark::BenchmarkRun,
) -> Result<ComparisonReport> {
let baseline = store.load(baseline_id)?;
Ok(ComparisonReport::new(&baseline, current, self.threshold))
}
/// Report comparison results
fn report_comparison(&self, report: &ComparisonReport, _verbose: bool) -> Result<()> {
// Print report
report.print_report();
// Export to Markdown if requested
if let Some(ref md_path) = self.export_markdown {
std::fs::write(md_path, report.to_markdown())?;
eprintln!("📄 Markdown report: {}", md_path.display());
}
// Export to JSON if requested
if let Some(ref json_path) = self.export_json {
std::fs::write(json_path, report.to_json()?)?;
eprintln!("📄 JSON report: {}", json_path.display());
}
// CI reporting
if self.ci_format.is_some() {
let format = if let Some(ref fmt) = self.ci_format {
fmt.parse::<CiFormat>()?
} else {
CiFormat::detect()
};
let reporter = CiReporter::new(format);
reporter.report_benchmarks(report);
}
// Fail if regressions detected
if self.fail_on_regression && report.has_regressions() {
anyhow::bail!(
"{} benchmark regression(s) detected (threshold: {:.1}%)",
report.regressions,
self.threshold
);
}
Ok(())
}
}