compile_benchmark.cpp 6.0 KB

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