forked from rust-lang/rustc-perf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollector.rs
More file actions
2502 lines (2221 loc) · 81.4 KB
/
collector.rs
File metadata and controls
2502 lines (2221 loc) · 81.4 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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![recursion_limit = "1024"]
use anyhow::Context;
use chrono::Utc;
use clap::builder::TypedValueParser;
use clap::{Arg, Parser};
use collector::compare::compare_artifacts;
use hashbrown::HashSet;
use humansize::{format_size, BINARY};
use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
use std::cmp::{Ordering, Reverse};
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::fs::File;
use std::future::Future;
use std::io::Write;
use std::io::{BufWriter, IsTerminal};
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::process;
use std::process::Command;
use std::str::FromStr;
use std::time::Duration;
use std::{str, time::Instant};
use tabled::builder::Builder;
use tabled::settings::object::{Columns, Rows};
use tabled::settings::style::Border;
use tabled::settings::{Alignment, Color, Modify, Width};
use tokio::runtime::Runtime;
use collector::artifact_stats::{
compile_and_get_stats, ArtifactStats, ArtifactWithStats, CargoProfile,
};
use collector::benchmark_set::{get_benchmark_set, BenchmarkSetId, BenchmarkSetMember};
use collector::codegen::{codegen_diff, CodegenType};
use collector::compile::benchmark::category::Category;
use collector::compile::benchmark::codegen_backend::CodegenBackend;
use collector::compile::benchmark::profile::Profile;
use collector::compile::benchmark::scenario::Scenario;
use collector::compile::benchmark::target::Target;
use collector::compile::benchmark::{
compile_benchmark_dir, get_compile_benchmarks, ArtifactType, Benchmark, BenchmarkName,
CompileBenchmarkFilter,
};
use collector::compile::execute::bencher::BenchProcessor;
use collector::compile::execute::profiler::{ProfileProcessor, Profiler};
use collector::runtime::{
bench_runtime, get_runtime_benchmark_groups, prepare_runtime_benchmark_suite,
runtime_benchmark_dir, BenchmarkSuite, BenchmarkSuiteCompilation, CargoIsolationMode,
RuntimeBenchmarkFilter, RuntimeProfiler, DEFAULT_RUNTIME_ITERATIONS,
};
use collector::runtime::{profile_runtime, RuntimeCompilationOpts};
use collector::toolchain::{
create_toolchain_from_published_version, get_local_toolchain, Sysroot, SysrootDownloadError,
Toolchain, ToolchainConfig,
};
use collector::utils::cachegrind::cachegrind_diff;
use collector::utils::{is_installed, wait_for_future};
use collector::{
command_output, utils, CollectorCtx, CollectorStepBuilder, LocalSelfProfileStorage,
S3SelfProfileStorage, SelfProfileStorage,
};
use database::{
ArtifactId, ArtifactIdNumber, BenchmarkJob, BenchmarkJobConclusion, CollectorConfig, Commit,
CommitType, Connection, Pool,
};
/// Directory used to cache downloaded Rust toolchains on disk.
const TOOLCHAIN_CACHE_DIRECTORY: &str = "cache";
/// Maximum allowed number of toolchains in the toolchain cache directory.
/// If the directory will have more toolchains, it will be purged.
const TOOLCHAIN_CACHE_MAX_TOOLCHAINS: usize = 30;
fn n_normal_benchmarks_remaining(n: usize) -> String {
let suffix = if n == 1 { "" } else { "s" };
format!("{n} normal benchmark{suffix} remaining")
}
struct BenchmarkErrors(usize);
impl BenchmarkErrors {
fn new() -> BenchmarkErrors {
BenchmarkErrors(0)
}
fn incr(&mut self) {
self.0 += 1;
}
fn add(&mut self, count: usize) {
self.0 += count;
}
fn fail_if_nonzero(self) -> anyhow::Result<()> {
if self.0 > 0 {
anyhow::bail!("{} benchmarks failed", self.0)
}
Ok(())
}
}
#[derive(Debug)]
struct BenchmarkDirs<'a> {
compile: &'a Path,
runtime: &'a Path,
}
struct CompileBenchmarkConfig {
benchmarks: Vec<Benchmark>,
profiles: Vec<Profile>,
scenarios: Vec<Scenario>,
backends: Vec<CodegenBackend>,
iterations: Option<usize>,
self_profile_storage: Option<Box<dyn SelfProfileStorage>>,
bench_rustc: bool,
targets: Vec<Target>,
}
struct RuntimeBenchmarkConfig {
runtime_suite: BenchmarkSuite,
filter: RuntimeBenchmarkFilter,
iterations: u32,
target: Target,
}
impl RuntimeBenchmarkConfig {
fn new(
suite: BenchmarkSuite,
filter: RuntimeBenchmarkFilter,
iterations: u32,
target: Target,
) -> Self {
Self {
runtime_suite: suite.filter(&filter),
filter,
iterations,
target,
}
}
}
struct SharedBenchmarkConfig {
artifact_id: ArtifactId,
toolchain: Toolchain,
job_id: Option<u32>,
}
fn check_measureme_installed() -> Result<(), String> {
let not_installed = IntoIterator::into_iter(["summarize", "crox", "flamegraph"])
.filter(|n| !is_installed(n))
.collect::<Vec<_>>();
if not_installed.is_empty() {
Ok(())
} else {
Err(format!("To run this command you need {0} on your PATH. To install run `cargo install --git https://github.com/rust-lang/measureme --branch stable {0}`\n", not_installed.join(" ")))
}
}
#[allow(clippy::too_many_arguments)]
fn generate_diffs(
id1: &str,
id2: &str,
out_dir: &Path,
benchmarks: &[Benchmark],
profiles: &[Profile],
scenarios: &[Scenario],
errors: &mut BenchmarkErrors,
profiler: &Profiler,
) -> Vec<PathBuf> {
let mut annotated_diffs = Vec::new();
for benchmark in benchmarks {
for &profile in profiles {
for scenario in scenarios.iter().flat_map(|scenario| {
if profile.is_doc() && scenario.is_incr() {
return vec![];
}
match scenario {
Scenario::Full | Scenario::IncrFull | Scenario::IncrUnchanged => {
vec![format!("{:?}", scenario)]
}
Scenario::IncrPatched => (0..benchmark.patches.len())
.map(|i| format!("{scenario:?}{i}"))
.collect::<Vec<_>>(),
}
}) {
let filename = |prefix, id| {
format!(
"{}-{}-{}-{:?}-{}{}",
prefix,
id,
benchmark.name,
profile,
scenario,
profiler.postfix()
)
};
let id_diff = format!("{id1}-{id2}");
let prefix = profiler.prefix();
let left = out_dir.join(filename(prefix, id1));
let right = out_dir.join(filename(prefix, id2));
let output = out_dir.join(filename(&format!("{prefix}-diff"), &id_diff));
if let Err(e) = profiler.diff(&left, &right, &output) {
errors.incr();
eprintln!("collector error: {e:?}");
continue;
}
annotated_diffs.push(output);
}
}
}
annotated_diffs
}
#[allow(clippy::too_many_arguments)]
fn profile_compile(
toolchain: &Toolchain,
profiler: Profiler,
out_dir: &Path,
benchmarks: &[Benchmark],
profiles: &[Profile],
scenarios: &[Scenario],
backends: &[CodegenBackend],
errors: &mut BenchmarkErrors,
targets: &[Target],
) {
eprintln!("Profiling {} with {:?}", toolchain.id, profiler);
if let Profiler::SelfProfile = profiler {
check_measureme_installed().unwrap();
}
let error_count: usize = benchmarks
.par_iter()
.enumerate()
.map(|(i, benchmark)| {
let benchmark_id = format!("{} ({}/{})", benchmark.name, i + 1, benchmarks.len());
eprintln!("Executing benchmark {benchmark_id}");
let mut processor = ProfileProcessor::new(profiler, out_dir, &toolchain.id);
let result = wait_for_future(benchmark.measure(
&mut processor,
profiles,
scenarios,
backends,
toolchain,
Some(1),
targets,
// We always want to profile everything
&hashbrown::HashSet::new(),
));
eprintln!("Finished benchmark {benchmark_id}");
if let Err(ref s) = result {
eprintln!(
"collector error: Failed to profile '{}' with {:?}, recorded: {:?}",
benchmark.name, profiler, s
);
1
} else {
0
}
})
.sum();
errors.add(error_count);
}
fn main() {
match main_result() {
Ok(code) => process::exit(code),
Err(err) => {
eprintln!("collector error: {err:?}");
process::exit(1);
}
}
}
/// We need to have a separate wrapper over a Vec<T>, otherwise Clap would incorrectly
/// assume that `EnumArgParser` parses a single item, rather than a list of items.
#[derive(Clone, Debug)]
struct MultiEnumValue<T>(Vec<T>);
/// Parser for enums (like profile or scenario) which can be passed either as a comma-delimited
/// string or as the "All" string, which selects all variants.
#[derive(Clone)]
struct EnumArgParser<T>(PhantomData<T>);
impl<T> Default for EnumArgParser<T> {
fn default() -> Self {
Self(Default::default())
}
}
impl<T: clap::ValueEnum + Sync + Send + 'static> TypedValueParser for EnumArgParser<T> {
type Value = MultiEnumValue<T>;
fn parse_ref(
&self,
cmd: &clap::Command,
arg: Option<&Arg>,
value: &OsStr,
) -> Result<Self::Value, clap::Error> {
if value == "All" {
Ok(MultiEnumValue(T::value_variants().to_vec()))
} else {
let values: Result<Vec<T>, _> = value
.to_str()
.unwrap()
.split(',')
.map(|item| clap::value_parser!(T).parse_ref(cmd, arg, OsStr::new(item)))
.collect();
Ok(MultiEnumValue(values?))
}
}
}
#[derive(Debug, clap::Parser)]
#[command(about, version, author)]
struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[test]
fn verify_cli() {
// By default, clap lazily checks subcommands. This provides eager testing
// without having to run the binary for each subcommand.
use clap::CommandFactory;
Cli::command().debug_assert()
}
#[derive(Debug, clap::Args)]
struct LocalOptions {
/// The path to the local rustc to measure
// Not a `PathBuf` because it can be a file path *or* a `+`-prefixed
// toolchain name, and `PathBuf` doesn't work well for the latter.
rustc: String,
/// Identifier to associate benchmark results with
#[arg(long)]
id: Option<String>,
/// The path to the local Cargo to use
#[arg(long)]
cargo: Option<PathBuf>,
/// Arguments passed to `cargo --config <value>`.
#[arg(long)]
cargo_config: Vec<String>,
/// Exclude all benchmarks matching a prefix in this comma-separated list
#[arg(long, value_delimiter = ',')]
exclude: Vec<String>,
/// Exclude all benchmarks matching a suffix in this comma-separated list
#[arg(long, value_delimiter = ',')]
exclude_suffix: Vec<String>,
/// Include only benchmarks matching a prefix in this comma-separated list
#[arg(long, value_delimiter = ',')]
include: Vec<String>,
/// Include only benchmarks in this comma-separated list
#[arg(
long,
value_delimiter = ',',
conflicts_with("include"),
conflicts_with("exclude"),
conflicts_with("exclude_suffix")
)]
exact_match: Vec<String>,
/// Include only benchmarks belonging to the given categories.
#[arg(long, value_parser = EnumArgParser::<Category>::default(), default_value = "Primary,Secondary")]
category: MultiEnumValue<Category>,
}
#[derive(Debug, clap::Args)]
struct CompileTimeOptions {
/// Measure the build profiles in this comma-separated list
#[arg(
long = "profiles",
alias = "builds", // the old name, for backward compatibility
value_parser = EnumArgParser::<Profile>::default(),
// Don't run rustdoc by default
default_value = "Check,Debug,Opt",
)]
profiles: MultiEnumValue<Profile>,
/// Measure the scenarios in this comma-separated list
#[arg(
long = "scenarios",
alias = "runs", // the old name, for backward compatibility
value_parser = EnumArgParser::<Scenario>::default(),
default_value = "All"
)]
scenarios: MultiEnumValue<Scenario>,
/// Measure the codegen backends in this comma-separated list
#[arg(long = "backends", value_parser = EnumArgParser::<CodegenBackend>::default(), default_value = "Llvm")]
codegen_backends: MultiEnumValue<CodegenBackend>,
/// The path to the local rustdoc to measure
#[arg(long)]
rustdoc: Option<PathBuf>,
/// The path to the local clippy to measure.
/// It should be a path to the `clippy-driver` binary.
#[arg(long)]
clippy: Option<PathBuf>,
}
#[derive(Debug, clap::Args)]
struct RuntimeOptions {
/// Select a runtime benchmark group that should be compiled and used. If not specified, all
/// found groups will be compiled.
#[arg(long)]
group: Option<String>,
}
#[derive(Debug, clap::Args)]
struct SelfProfileOption {
/// Collect self-profile data
#[arg(long = "self-profile")]
self_profile: bool,
}
#[derive(Debug, clap::Args)]
struct DbOption {
/// Database output file
// This would be better as a `PathBuf`, but it's used in various ways that
// make that tricky without adjusting several points in the code.
#[arg(long, default_value = "results.db", env = "DATABASE_URL")]
db: String,
}
#[derive(Debug, clap::Args)]
struct BenchRustcOption {
/// Run the special `rustc` benchmark
#[arg(long = "bench-rustc")]
bench_rustc: bool,
}
#[derive(Clone, Debug, clap::ValueEnum)]
enum PurgeMode {
/// Purge all old data associated with the artifact
Old,
/// Purge old data of failed benchmarks associated with the artifact
Failed,
}
#[derive(Debug, clap::Args)]
struct PurgeOption {
/// Removes old data for the specified artifact prior to running the benchmarks.
#[arg(long = "purge")]
purge: Option<PurgeMode>,
}
#[derive(Debug, clap::Args)]
#[command(rename_all = "snake_case")]
struct BinaryStatsCompile {
#[command(flatten)]
local: LocalOptions,
/// Cargo profile to use.
#[arg(long, default_value = "Debug")]
profile: Profile,
/// Codegen backend to use.
#[arg(long = "backend", default_value = "Llvm")]
codegen_backend: CodegenBackend,
/// An optional second toolchain to compare to.
#[arg(long)]
rustc2: Option<String>,
/// Codegen backend to use for the second toolchain.
#[arg(long = "backend2")]
codegen_backend2: Option<CodegenBackend>,
}
#[derive(Debug, clap::Args)]
#[command(rename_all = "snake_case")]
struct BinaryStatsLocal {
/// Binary artifact to examine.
artifact: PathBuf,
/// Optional second artifact to compare with the first one.
artifact2: Option<PathBuf>,
}
#[derive(Debug, clap::Subcommand)]
#[command(rename_all = "snake_case")]
enum BinaryStatsMode {
/// Show size statistics for the selected compile benchmark(s).
/// Optionally compares sizes between two compiler toolchains, if `--rustc2` is provided.
Compile(BinaryStatsCompile),
/// Show size statistics for the selected binary artifact on disk.
/// Optionally compares sizes with a second provided artifact.
Local(BinaryStatsLocal),
}
// For each subcommand we list the mandatory arguments in the required
// order, followed by the options in alphabetical order.
#[derive(Debug, clap::Subcommand)]
#[command(rename_all = "snake_case")]
enum Commands {
/// Show binary (executable or library) section (and optionally symbol) size statistics.
BinaryStats {
/// Also print symbol comparison in addition to section comparison.
///
/// Warning: may generate *A LOT* of data.
#[arg(long, default_value_t = false, global = true)]
symbols: bool,
#[clap(subcommand)]
mode: BinaryStatsMode,
},
/// Benchmarks the performance of programs generated by a local rustc
BenchRuntimeLocal {
#[command(flatten)]
local: LocalOptions,
#[command(flatten)]
runtime: RuntimeOptions,
/// How many iterations of each benchmark should be executed.
#[arg(long, default_value_t = DEFAULT_RUNTIME_ITERATIONS)]
iterations: u32,
#[command(flatten)]
db: DbOption,
/// Compile runtime benchmarks directly in their crate directory, to make local experiments
/// faster.
#[arg(long = "no-isolate")]
no_isolate: bool,
#[command(flatten)]
purge: PurgeOption,
},
/// Profiles a runtime benchmark.
ProfileRuntime {
#[command(flatten)]
runtime: RuntimeOptions,
/// Profiler to use
profiler: RuntimeProfiler,
/// The path to the local rustc used to compile the runtime benchmark
rustc: String,
/// The path to a second local rustc used to compare with the baseline rustc
#[arg(long)]
rustc2: Option<String>,
/// Name of the benchmark that should be profiled
benchmark: String,
},
/// Displays the diff between assembly, LLVM or MIR for a runtime benchmark group.
CodegenDiff {
/// Profiler to use
codegen_type: CodegenType,
/// Runtime benchmark group to diff (name of a directory in `collector/runtime-benchmarks`)
group: String,
/// The path to the local rustc used to compile the runtime benchmark
rustc1: String,
/// The path to a second rustc used to compile with the baseline
rustc2: String,
},
/// Benchmarks a local rustc
BenchLocal {
#[command(flatten)]
local: LocalOptions,
#[command(flatten)]
opts: CompileTimeOptions,
#[command(flatten)]
db: DbOption,
#[command(flatten)]
bench_rustc: BenchRustcOption,
/// The number of iterations to do for each benchmark
#[arg(long, default_value = "1")]
iterations: usize,
#[command(flatten)]
self_profile: SelfProfileOption,
#[command(flatten)]
purge: PurgeOption,
},
/// Benchmarks a published toolchain for perf.rust-lang.org's dashboard
BenchPublished {
/// Toolchain (e.g. stable, beta, 1.26.0)
toolchain: String,
#[command(flatten)]
db: DbOption,
},
/// Profiles a local rustc with one of several profilers
ProfileLocal {
/// Profiler to use
#[arg(value_enum)]
profiler: Profiler,
#[command(flatten)]
local: LocalOptions,
#[command(flatten)]
opts: CompileTimeOptions,
/// Output directory
#[arg(long = "out-dir", default_value = "results/")]
out_dir: PathBuf,
/// The path to the second local rustc (to diff against)
// Not a `PathBuf` because it can be a file path *or* a `+`-prefixed
// toolchain name, and `PathBuf` doesn't work well for the latter.
#[arg(long)]
rustc2: Option<String>,
/// How many benchmarks should be profiled in parallel.
/// This flag is only supported for certain profilers
#[arg(long, short = 'j', default_value = "1")]
jobs: u64,
},
/// Installs the next commit for perf.rust-lang.org
InstallNext {
/// Install additional components to enable benchmarking of the given backends.
#[arg(long = "backends", value_parser = EnumArgParser::<CodegenBackend>::default(), default_value = "Llvm")]
codegen_backends: MultiEnumValue<CodegenBackend>,
},
/// Download a crate into collector/benchmarks.
Download(DownloadCommand),
/// Removes all data associated with artifact(s) with the given name.
PurgeArtifact {
/// Name of the artifact.
name: String,
#[command(flatten)]
db: DbOption,
},
/// Displays diff between two local bench results.
BenchCmp {
#[command(flatten)]
db: DbOption,
/// Metric used to compare artifacts.
#[arg(long)]
metric: Option<database::metric::Metric>,
/// The name of the base artifact to be compared.
base: Option<String>,
/// The name of the modified artifact to be compared.
modified: Option<String>,
},
/// Registers a new collector in the database.
/// Use `--is_active` to immediately mark the collector as active.
AddCollector {
#[command(flatten)]
db: DbOption,
/// Name of the collector.
#[arg(long)]
collector_name: String,
/// Target tuple which will the collector be benchmarking.
#[arg(long)]
target: String,
/// Should the collector be marked as active immediately?
/// Only active collectors will receive jobs.
#[arg(long)]
is_active: bool,
/// The benchmark set index that the collector will be benchmarking.
#[arg(long)]
benchmark_set: u32,
},
/// Benchmark test cases pulled from the job queue.
BenchmarkJobQueue {
/// The unique identifier for the collector.
/// It has to exist in the database; you can create new collectors using the `add_collector`
/// command.
#[arg(long)]
collector_name: String,
/// Git SHA of the commit that the collector is currently on.
/// If not present, the collector will attempt to figure it out from git directly.
#[arg(long)]
git_sha: Option<String>,
/// Periodically check if the collector's commit SHA matches the commit SHA of the
/// rustc-perf repository.
#[arg(long)]
check_git_sha: bool,
#[command(flatten)]
db: DbOption,
},
}
#[derive(Debug, clap::Parser)]
struct DownloadCommand {
/// Name of the benchmark created directory
#[arg(long, global = true)]
name: Option<String>,
/// Overwrite the benchmark directory if it already exists
#[arg(long, short('f'), global = true)]
force: bool,
/// What category does the benchmark belong to
#[arg(long, short('c'), value_enum, global = true, default_value = "Primary")]
category: Category,
/// What artifact type (library or binary) does the benchmark build.
#[arg(long, short('a'), value_enum, global = true, default_value = "library")]
artifact: ArtifactType,
#[command(subcommand)]
command: DownloadSubcommand,
}
#[derive(Debug, clap::Parser)]
enum DownloadSubcommand {
/// Download a crate from a git repository.
Git { url: String },
/// Download a crate from crates.io.
Crate {
#[arg(value_name = "CRATE")]
krate: String,
version: String,
},
}
impl<'a> From<&'a LocalOptions> for CompileBenchmarkFilter<'a> {
fn from(value: &'a LocalOptions) -> Self {
if !value.exact_match.is_empty() {
Self::Exact(&value.exact_match)
} else if !value.include.is_empty()
|| !value.exclude.is_empty()
|| !value.exclude_suffix.is_empty()
{
Self::Fuzzy {
include: &value.include,
exclude: &value.exclude,
exclude_suffix: &value.exclude_suffix,
}
} else {
Self::All
}
}
}
fn main_result() -> anyhow::Result<i32> {
env_logger::init();
let args = Cli::parse();
let compile_benchmark_dir = compile_benchmark_dir();
let runtime_benchmark_dir = runtime_benchmark_dir();
let benchmark_dirs = BenchmarkDirs {
compile: &compile_benchmark_dir,
runtime: &runtime_benchmark_dir,
};
// We need to find the host tuple for a couple of things (several collector commands need it).
// Probably the simplest way of determining it is asking rustc what is its host tuple.
// However, where to get that rustc? We could just try using "rustc", but that is not always
// available, e.g. on Rust's CI.
// So we try to figure out if we have some rustc available from the command that is being
// executed; such rustc should definitely be executable on this host.
// If we don't, we'll simply fall back to `rustc`.
let used_rustc: Option<String> = match &args.command {
Commands::BinaryStats {
mode: BinaryStatsMode::Compile(args),
..
} => Some(args.local.rustc.clone()),
Commands::BenchRuntimeLocal { local, .. } => Some(local.rustc.clone()),
Commands::ProfileRuntime { rustc, .. } => Some(rustc.clone()),
Commands::CodegenDiff { rustc1, .. } => Some(rustc1.clone()),
Commands::BenchLocal { local, .. } => Some(local.rustc.clone()),
Commands::ProfileLocal { local, .. } => Some(local.rustc.clone()),
Commands::BinaryStats {
mode: BinaryStatsMode::Local(_),
..
}
| Commands::BenchPublished { .. }
| Commands::InstallNext { .. }
| Commands::Download(_)
| Commands::PurgeArtifact { .. }
| Commands::BenchCmp { .. }
| Commands::AddCollector { .. }
| Commands::BenchmarkJobQueue { .. } => None,
};
let host_target_tuple = match used_rustc {
Some(rustc) if !rustc.starts_with("+") => get_host_tuple_from_rustc(&rustc),
_ => get_host_tuple_from_rustc("rustc"),
};
// We only unwrap the host tuple in places where we actually need it, to avoid panicking if it
// is missing, but we don't really need it.
let require_host_target_tuple = || {
host_target_tuple.expect(
"Cannot determine host target tuple. Please make a `rustc` binary available in PATH.",
)
};
match args.command {
Commands::BinaryStats { mode, symbols } => {
match mode {
BinaryStatsMode::Compile(args) => {
binary_stats_compile(args, symbols, &require_host_target_tuple())?;
}
BinaryStatsMode::Local(args) => {
binary_stats_local(args, symbols)?;
}
}
Ok(0)
}
Commands::BenchRuntimeLocal {
local,
runtime,
iterations,
db,
no_isolate,
purge,
} => {
log_db(&db);
let host_tuple = require_host_target_tuple();
let toolchain = get_local_toolchain_for_runtime_benchmarks(&local, &host_tuple)?;
let pool = Pool::open(&db.db);
let isolation_mode = if no_isolate {
CargoIsolationMode::Cached
} else {
CargoIsolationMode::Isolated
};
let rt = build_async_runtime();
let mut conn = rt.block_on(pool.connection());
let artifact_id = ArtifactId::Commit(Commit {
sha: toolchain.id.clone(),
date: Utc::now().into(),
r#type: CommitType::Master,
});
rt.block_on(purge_old_data(conn.as_mut(), &artifact_id, purge.purge));
let runtime_suite = rt.block_on(load_runtime_benchmarks(
conn.as_mut(),
&runtime_benchmark_dir,
isolation_mode,
runtime.group,
&toolchain,
&artifact_id,
None,
))?;
let shared = SharedBenchmarkConfig {
artifact_id,
toolchain,
job_id: None,
};
let config = RuntimeBenchmarkConfig::new(
runtime_suite,
RuntimeBenchmarkFilter::new(local.exclude, local.include),
iterations,
Target::from_str(&host_tuple).expect("Found unexpected host target"),
);
rt.block_on(run_benchmarks(conn.as_mut(), shared, None, Some(config)))?;
Ok(0)
}
Commands::ProfileRuntime {
runtime,
profiler,
rustc,
rustc2,
benchmark,
} => {
let host_target_tuple = require_host_target_tuple();
let get_suite = |rustc: &str, id: &str| {
let toolchain = get_local_toolchain(
&[Profile::Opt],
&[CodegenBackend::Llvm],
rustc,
ToolchainConfig::default(),
id,
host_target_tuple.clone(),
)?;
let suite = prepare_runtime_benchmark_suite(
&toolchain,
&runtime_benchmark_dir,
CargoIsolationMode::Cached,
runtime.group.clone(),
// Compile with debuginfo to have filenames and line numbers available in the
// generated profiles.
RuntimeCompilationOpts::default().debug_info("1"),
)?
.extract_suite();
Ok::<_, anyhow::Error>((toolchain, suite))
};
println!("Profiling {rustc}");
let (toolchain1, suite1) = get_suite(&rustc, "1")?;
let profile1 = profile_runtime(profiler.clone(), &toolchain1, suite1, &benchmark)?;
if let Some(rustc2) = rustc2 {
match profiler {
RuntimeProfiler::Cachegrind => {
println!("Profiling {rustc2}");
let (toolchain2, suite2) = get_suite(&rustc2, "2")?;
let profile2 = profile_runtime(profiler, &toolchain2, suite2, &benchmark)?;
let output = profile1.parent().unwrap().join(format!(
"cgann-diff-{}-{}-{benchmark}",
toolchain1.id, toolchain2.id
));
cachegrind_diff(&profile1, &profile2, &output)
.context("Cannot generate Cachegrind diff")?;
println!("Cachegrind diff stored in `{}`", output.display());
}
}
} else {
println!(
"Profiling complete, result can be found in `{}`",
profile1.display()
);
}
Ok(0)
}
Commands::CodegenDiff {
codegen_type,
group,
rustc1: rustc,
rustc2,
} => {
let host_target_tuple = require_host_target_tuple();
let get_toolchain = |rustc: &str, id: &str| {
let toolchain = get_local_toolchain(
&[Profile::Opt],
&[CodegenBackend::Llvm],
rustc,
ToolchainConfig::default(),
id,
host_target_tuple.clone(),
)?;
Ok::<_, anyhow::Error>(toolchain)
};
let toolchain1 = get_toolchain(&rustc, "1")?;
let toolchain2 = get_toolchain(&rustc2, "2")?;
let mut benchmark_groups =
get_runtime_benchmark_groups(&runtime_benchmark_dir, Some(group))?;
let group = benchmark_groups.pop().expect("Benchmark group not found");
assert!(benchmark_groups.is_empty());
codegen_diff(codegen_type, toolchain1, toolchain2, group)?;
Ok(0)
}
Commands::BenchLocal {
local,
opts,
db,
bench_rustc,
iterations,
self_profile,
purge,
} => {
log_db(&db);
let profiles = opts.profiles.0;