compile_benchmark.cpp 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include <benchmark/benchmark.h>
  5. #include <string>
  6. #include "testing/base/global_exe_path.h"
  7. #include "testing/base/source_gen.h"
  8. #include "toolchain/driver/driver.h"
  9. #include "toolchain/install/install_paths_test_helpers.h"
  10. namespace Carbon::Testing {
  11. namespace {
  12. // Helper used to benchmark compilation across different phases.
  13. //
  14. // Handles setting up the compiler's driver, locating the prelude, and managing
  15. // a VFS in which the compilations occur.
  16. class CompileBenchmark {
  17. public:
  18. CompileBenchmark()
  19. : installation_(InstallPaths::MakeForBazelRunfiles(GetExePath())),
  20. driver_(fs_, &installation_, llvm::outs(), llvm::errs()) {
  21. AddPreludeFilesToVfs(installation_, &fs_);
  22. }
  23. // Setup a set of source files in the VFS for the driver. Each string input is
  24. // materialized into a virtual file and a list of the virtual filenames is
  25. // returned.
  26. auto SetUpFiles(llvm::ArrayRef<std::string> sources)
  27. -> llvm::OwningArrayRef<std::string> {
  28. llvm::OwningArrayRef<std::string> file_names(sources.size());
  29. for (ssize_t i : llvm::seq<ssize_t>(sources.size())) {
  30. file_names[i] = llvm::formatv("file_{0}.carbon", i).str();
  31. fs_.addFile(file_names[i], /*ModificationTime=*/0,
  32. llvm::MemoryBuffer::getMemBuffer(sources[i]));
  33. }
  34. return file_names;
  35. }
  36. auto driver() -> Driver& { return driver_; }
  37. auto gen() -> SourceGen& { return gen_; }
  38. private:
  39. llvm::vfs::InMemoryFileSystem fs_;
  40. const InstallPaths installation_;
  41. Driver driver_;
  42. SourceGen gen_;
  43. };
  44. // An enumerator used to select compilation phases to benchmark.
  45. enum class Phase {
  46. Lex,
  47. Parse,
  48. Check,
  49. };
  50. // Maps the enumerator for a compilation phase into a specific `compile` command
  51. // line flag.
  52. static auto PhaseFlag(Phase phase) -> llvm::StringRef {
  53. switch (phase) {
  54. case Phase::Lex:
  55. return "--phase=lex";
  56. case Phase::Parse:
  57. return "--phase=parse";
  58. case Phase::Check:
  59. return "--phase=check";
  60. }
  61. }
  62. // Benchmark on multiple files of the same size but with different source code
  63. // in order to avoid branch prediction perfectly learning a particular file's
  64. // structure and shape, and to get closer to a cache-cold benchmark number which
  65. // is what we generally expect to care about in practice. We enforce an upper
  66. // bound to avoid excessive benchmark time and a lower bound to avoid anchoring
  67. // on a single source file that may have unrepresentative content.
  68. //
  69. // For simplicity, we compute a number of files from the target line count as a
  70. // heuristic.
  71. static auto ComputeFileCount(int target_lines) -> int {
  72. #ifndef NDEBUG
  73. // Use a smaller number of files in debug builds where compiles are slower.
  74. return std::max(1, std::min(8, (1024 * 1024) / target_lines));
  75. #else
  76. return std::max(8, std::min(1024, (1024 * 1024) / target_lines));
  77. #endif
  78. }
  79. template <Phase P>
  80. static auto BM_CompileAPIFileDenseDecls(benchmark::State& state) -> void {
  81. CompileBenchmark bench;
  82. int target_lines = state.range(0);
  83. int num_files = ComputeFileCount(target_lines);
  84. llvm::OwningArrayRef<std::string> sources(num_files);
  85. // Create a collection of random source files. Average the actual number of
  86. // lines resulting so we can use that to compute the compilation speed as a
  87. // line-rate counter.
  88. double avg_lines = 0.0;
  89. for (std::string& source : sources) {
  90. source = bench.gen().GenAPIFileDenseDecls(target_lines,
  91. SourceGen::DenseDeclParams{});
  92. avg_lines += llvm::count(source, '\n');
  93. }
  94. avg_lines /= sources.size();
  95. // Setup the sources as files for compilation.
  96. llvm::OwningArrayRef<std::string> file_names = bench.SetUpFiles(sources);
  97. CARBON_CHECK(static_cast<int>(file_names.size()) == num_files);
  98. // We benchmark in batches of files to avoid benchmarking any peculiarities of
  99. // a single file.
  100. while (state.KeepRunningBatch(num_files)) {
  101. for (ssize_t i = 0; i < num_files;) {
  102. // We block optimizing `i` as that has proven both more effective at
  103. // blocking the loop from being optimized away and avoiding disruption of
  104. // the generated code that we're benchmarking.
  105. benchmark::DoNotOptimize(i);
  106. bool success = bench.driver()
  107. .RunCommand({"compile", PhaseFlag(P), file_names[i]})
  108. .success;
  109. CARBON_DCHECK(success);
  110. // We use the compilation success to step through the file names,
  111. // establishing a dependency between each lookup. This doesn't fully allow
  112. // us to measure latency rather than throughput, but minimizes any skew in
  113. // measurements from speculating the start of the next compilation.
  114. i += static_cast<ssize_t>(success);
  115. }
  116. }
  117. // Compute the line-rate of these compilations.
  118. state.counters["Lines"] = benchmark::Counter(
  119. avg_lines, benchmark::Counter::kIsIterationInvariantRate);
  120. }
  121. // Benchmark from 256-line test cases through 256k line test cases, and for each
  122. // phase of compilation.
  123. BENCHMARK(BM_CompileAPIFileDenseDecls<Phase::Lex>)
  124. ->RangeMultiplier(4)
  125. ->Range(256, static_cast<int64_t>(256 * 1024));
  126. BENCHMARK(BM_CompileAPIFileDenseDecls<Phase::Parse>)
  127. ->RangeMultiplier(4)
  128. ->Range(256, static_cast<int64_t>(256 * 1024));
  129. BENCHMARK(BM_CompileAPIFileDenseDecls<Phase::Check>)
  130. ->RangeMultiplier(4)
  131. ->Range(256, static_cast<int64_t>(256 * 1024));
  132. } // namespace
  133. } // namespace Carbon::Testing