compile_benchmark.cpp 6.0 KB

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