compile_benchmark.cpp 6.1 KB

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