compile_benchmark.cpp 6.1 KB

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