tokenized_buffer_benchmark.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 "absl/random/random.h"
  7. #include "common/check.h"
  8. #include "llvm/ADT/Sequence.h"
  9. #include "llvm/ADT/StringExtras.h"
  10. #include "toolchain/diagnostics/diagnostic_emitter.h"
  11. #include "toolchain/diagnostics/null_diagnostics.h"
  12. #include "toolchain/lex/token_kind.h"
  13. #include "toolchain/lex/tokenized_buffer.h"
  14. namespace Carbon::Testing {
  15. namespace {
  16. using Lex::TokenizedBuffer;
  17. using Lex::TokenKind;
  18. // A large value for measurement stability without making benchmarking too slow.
  19. // Needs to be a multiple of 100 so we can easily divide it up into percentages,
  20. // and 1% itself needs to not be too tiny. This makes 100,000 a great balance.
  21. constexpr int NumTokens = 100'000;
  22. auto IdentifierStartChars() -> llvm::ArrayRef<char> {
  23. static llvm::SmallVector<char> chars = [] {
  24. llvm::SmallVector<char> chars;
  25. chars.push_back('_');
  26. for (char c : llvm::seq_inclusive('A', 'Z')) {
  27. chars.push_back(c);
  28. }
  29. for (char c : llvm::seq_inclusive('a', 'z')) {
  30. chars.push_back(c);
  31. }
  32. return chars;
  33. }();
  34. return chars;
  35. }
  36. auto IdentifierChars() -> llvm::ArrayRef<char> {
  37. static llvm::SmallVector<char> chars = [] {
  38. llvm::ArrayRef<char> start_chars = IdentifierStartChars();
  39. llvm::SmallVector<char> chars(start_chars.begin(), start_chars.end());
  40. for (char c : llvm::seq_inclusive('0', '9')) {
  41. chars.push_back(c);
  42. }
  43. return chars;
  44. }();
  45. return chars;
  46. }
  47. // Generates a random identifier string of the specified length using the
  48. // provided RNG BitGen.
  49. auto GenerateRandomIdentifier(absl::BitGen& gen, int length) -> std::string {
  50. llvm::ArrayRef<char> start_chars = IdentifierStartChars();
  51. llvm::ArrayRef<char> chars = IdentifierChars();
  52. std::string id_result;
  53. llvm::raw_string_ostream os(id_result);
  54. llvm::StringRef id;
  55. do {
  56. // Erase any prior attempts to find an identifier.
  57. id_result.clear();
  58. os << start_chars[absl::Uniform<int>(gen, 0, start_chars.size())];
  59. for (int j : llvm::seq(0, length)) {
  60. static_cast<void>(j);
  61. os << chars[absl::Uniform<int>(gen, 0, chars.size())];
  62. }
  63. // Check if we ended up forming an integer type literal or a keyword, and
  64. // try again.
  65. id = llvm::StringRef(id_result);
  66. } while (
  67. llvm::any_of(TokenKind::KeywordTokens,
  68. [id](auto token) { return id == token.fixed_spelling(); }) ||
  69. ((id.consume_front("i") || id.consume_front("u") ||
  70. id.consume_front("f")) &&
  71. llvm::all_of(id, [](const char c) { return llvm::isDigit(c); })));
  72. return id_result;
  73. }
  74. // Get a static pool of random identifiers with the desired distribution.
  75. template <int MinLength = 1, int MaxLength = 64, bool Uniform = false>
  76. auto GetRandomIdentifiers() -> const std::array<std::string, NumTokens>& {
  77. static_assert(MinLength <= MaxLength);
  78. static_assert(
  79. Uniform || MaxLength <= 64,
  80. "Cannot produce a meaningful non-uniform distribution of lengths longer "
  81. "than 64 as those are exceedingly rare in our observed data sets.");
  82. static const std::array<std::string, NumTokens> id_storage = [] {
  83. std::array<int, 64> id_length_counts;
  84. // For non-uniform distribution, we simulate a distribution roughly based on
  85. // the observed histogram of identifier lengths, but smoothed a bit and
  86. // reduced to small counts so that we cycle through all the lengths
  87. // reasonably quickly. We want sampling of even 10% of NumTokens from this
  88. // in a round-robin form to not be skewed overly much. This still inherently
  89. // compresses the long tail as we'd rather have coverage even though it
  90. // distorts the distribution a bit.
  91. //
  92. // The distribution here comes from a script that analyzes source code run
  93. // over a few directories of LLVM. The script renders a visual ascii-art
  94. // histogram along with the data for each bucket, and that output is
  95. // included in comments above each bucket size below to help visualize the
  96. // rough shape we're aiming for.
  97. //
  98. // 1 characters [3976] ███████████████████████████████▊
  99. id_length_counts[0] = 40;
  100. // 2 characters [3724] █████████████████████████████▊
  101. id_length_counts[1] = 40;
  102. // 3 characters [4173] █████████████████████████████████▍
  103. id_length_counts[2] = 40;
  104. // 4 characters [5000] ████████████████████████████████████████
  105. id_length_counts[3] = 50;
  106. // 5 characters [1568] ████████████▌
  107. id_length_counts[4] = 20;
  108. // 6 characters [2226] █████████████████▊
  109. id_length_counts[5] = 20;
  110. // 7 characters [2380] ███████████████████
  111. id_length_counts[6] = 20;
  112. // 8 characters [1786] ██████████████▎
  113. id_length_counts[7] = 18;
  114. // 9 characters [1397] ███████████▏
  115. id_length_counts[8] = 12;
  116. // 10 characters [ 739] █████▉
  117. id_length_counts[9] = 12;
  118. // 11 characters [ 779] ██████▎
  119. id_length_counts[10] = 12;
  120. // 12 characters [1344] ██████████▊
  121. id_length_counts[11] = 12;
  122. // 13 characters [ 498] ████
  123. id_length_counts[12] = 5;
  124. // 14 characters [ 284] ██▎
  125. id_length_counts[13] = 3;
  126. // 15 characters [ 172] █▍
  127. // 16 characters [ 278] ██▎
  128. // 17 characters [ 191] █▌
  129. // 18 characters [ 207] █▋
  130. for (int i : llvm::seq(14, 18)) {
  131. id_length_counts[i] = 2;
  132. }
  133. // 19 - 63 characters are all <100 but non-zero, and we map them to 1 for
  134. // coverage despite slightly over weighting the tail.
  135. for (int i : llvm::seq(18, 64)) {
  136. id_length_counts[i] = 1;
  137. }
  138. // Used to track the different count buckets when in a non-uniform
  139. // distribution.
  140. int length_bucket_index = 0;
  141. int length_count = 0;
  142. std::array<std::string, NumTokens> ids;
  143. absl::BitGen gen;
  144. for (auto [i, id] : llvm::enumerate(ids)) {
  145. if (Uniform) {
  146. // Rather than using randomness, for a uniform distribution rotate
  147. // lengths in round-robin to get a deterministic and exact size on every
  148. // run. We will then shuffle them at the end to produce a random
  149. // ordering.
  150. int length = MinLength + i % (1 + MaxLength - MinLength);
  151. id = GenerateRandomIdentifier(gen, length);
  152. continue;
  153. }
  154. // For non-uniform distribution, walk through each each length bucket
  155. // until our count matches the desired distribution, and then move to the
  156. // next.
  157. id = GenerateRandomIdentifier(gen, length_bucket_index + 1);
  158. if (length_count < id_length_counts[length_bucket_index]) {
  159. ++length_count;
  160. } else {
  161. length_bucket_index =
  162. (length_bucket_index + 1) % id_length_counts.size();
  163. length_count = 0;
  164. }
  165. }
  166. return ids;
  167. }();
  168. return id_storage;
  169. }
  170. // Compute a random sequence of just identifiers.
  171. template <int MinLength = 1, int MaxLength = 64, bool Uniform = false>
  172. auto RandomIdentifierSeq() -> std::string {
  173. // Get a static pool of identifiers with the desired distribution.
  174. const std::array<std::string, NumTokens>& ids =
  175. GetRandomIdentifiers<MinLength, MaxLength, Uniform>();
  176. // Shuffle tokens so we get exactly one of each identifier but in a random
  177. // order.
  178. std::array<llvm::StringRef, NumTokens> tokens;
  179. for (int i : llvm::seq(NumTokens)) {
  180. tokens[i] = ids[i];
  181. }
  182. std::shuffle(tokens.begin(), tokens.end(), absl::BitGen());
  183. return llvm::join(tokens, " ");
  184. }
  185. auto GetSymbolTokenTable() -> llvm::ArrayRef<TokenKind> {
  186. // Build our own table of symbols so we can use repetitions to skew the
  187. // distribution.
  188. static auto symbol_token_table_storage = [] {
  189. llvm::SmallVector<TokenKind> table;
  190. #define CARBON_SYMBOL_TOKEN(TokenName, Spelling) \
  191. table.push_back(TokenKind::TokenName);
  192. #define CARBON_OPENING_GROUP_SYMBOL_TOKEN(TokenName, Spelling, ClosingName)
  193. #define CARBON_CLOSING_GROUP_SYMBOL_TOKEN(TokenName, Spelling, OpeningName)
  194. #include "toolchain/lex/token_kind.def"
  195. table.insert(table.end(), 32, TokenKind::Semi);
  196. table.insert(table.end(), 16, TokenKind::Comma);
  197. table.insert(table.end(), 12, TokenKind::Period);
  198. table.insert(table.end(), 8, TokenKind::Colon);
  199. table.insert(table.end(), 8, TokenKind::Equal);
  200. table.insert(table.end(), 4, TokenKind::Amp);
  201. table.insert(table.end(), 4, TokenKind::ColonExclaim);
  202. table.insert(table.end(), 4, TokenKind::EqualEqual);
  203. table.insert(table.end(), 4, TokenKind::ExclaimEqual);
  204. table.insert(table.end(), 4, TokenKind::MinusGreater);
  205. table.insert(table.end(), 4, TokenKind::Star);
  206. return table;
  207. }();
  208. return symbol_token_table_storage;
  209. }
  210. // Compute a random sequence of mixed symbols, keywords, and identifiers, with
  211. // percentages of each according to the parameters.
  212. auto RandomMixedSeq(int symbol_percent, int keyword_percent) -> std::string {
  213. CARBON_CHECK(0 <= symbol_percent && symbol_percent <= 100)
  214. << "Must be a percent: [0, 100].";
  215. CARBON_CHECK(0 <= keyword_percent && keyword_percent <= 100)
  216. << "Must be a percent: [0, 100].";
  217. CARBON_CHECK((symbol_percent + keyword_percent) <= 100)
  218. << "Cannot have >100%.";
  219. static_assert((NumTokens % 100) == 0,
  220. "The number of tokens must be divisible by 100 so that we can "
  221. "easily scale integer percentages up to it.");
  222. // Get static pools of symbols, keywords, and identifiers.
  223. llvm::ArrayRef<TokenKind> symbols = GetSymbolTokenTable();
  224. llvm::ArrayRef<TokenKind> keywords = TokenKind::KeywordTokens;
  225. const std::array<std::string, NumTokens>& ids = GetRandomIdentifiers();
  226. // Build a list of StringRefs from the different types with the desired
  227. // distribution, then shuffle that list.
  228. std::array<llvm::StringRef, NumTokens> tokens;
  229. int num_symbols = (NumTokens / 100) * symbol_percent;
  230. int num_keywords = (NumTokens / 100) * keyword_percent;
  231. int num_identifiers = NumTokens - num_symbols - num_keywords;
  232. CARBON_CHECK(num_identifiers == 0 || num_identifiers > 500)
  233. << "We require at least 500 identifiers as we need to collect a "
  234. "reasonable number of samples to end up with a reasonable "
  235. "distribution of lengths.";
  236. for (int i : llvm::seq(num_symbols)) {
  237. tokens[i] = symbols[i % symbols.size()].fixed_spelling();
  238. }
  239. for (int i : llvm::seq(num_keywords)) {
  240. tokens[num_symbols + i] = keywords[i % keywords.size()].fixed_spelling();
  241. }
  242. for (int i : llvm::seq(num_identifiers)) {
  243. // We always have enough identifiers, so no need to mod here.
  244. tokens[num_symbols + num_keywords + i] = ids[i];
  245. }
  246. std::shuffle(tokens.begin(), tokens.end(), absl::BitGen());
  247. return llvm::join(tokens, " ");
  248. }
  249. class LexerBenchHelper {
  250. public:
  251. explicit LexerBenchHelper(llvm::StringRef text)
  252. : source_(MakeSourceBuffer(text)) {}
  253. auto Lex() -> TokenizedBuffer {
  254. DiagnosticConsumer& consumer = NullDiagnosticConsumer();
  255. return TokenizedBuffer::Lex(source_, consumer);
  256. }
  257. auto DiagnoseErrors() -> std::string {
  258. std::string result;
  259. llvm::raw_string_ostream out(result);
  260. StreamDiagnosticConsumer consumer(out);
  261. auto buffer = TokenizedBuffer::Lex(source_, consumer);
  262. consumer.Flush();
  263. CARBON_CHECK(buffer.has_errors())
  264. << "Asked to diagnose errors but none found!";
  265. return result;
  266. }
  267. private:
  268. auto MakeSourceBuffer(llvm::StringRef text) -> SourceBuffer {
  269. CARBON_CHECK(fs_.addFile(filename_, /*ModificationTime=*/0,
  270. llvm::MemoryBuffer::getMemBuffer(text)));
  271. return std::move(*SourceBuffer::CreateFromFile(
  272. fs_, filename_, ConsoleDiagnosticConsumer()));
  273. }
  274. llvm::vfs::InMemoryFileSystem fs_;
  275. std::string filename_ = "test.carbon";
  276. SourceBuffer source_;
  277. };
  278. void BM_ValidKeywords(benchmark::State& state) {
  279. absl::BitGen gen;
  280. std::array<llvm::StringRef, NumTokens> tokens;
  281. for (int i : llvm::seq(NumTokens)) {
  282. tokens[i] = TokenKind::KeywordTokens[i % TokenKind::KeywordTokens.size()]
  283. .fixed_spelling();
  284. }
  285. std::shuffle(tokens.begin(), tokens.end(), gen);
  286. std::string source = llvm::join(tokens, " ");
  287. LexerBenchHelper helper(source);
  288. for (auto _ : state) {
  289. TokenizedBuffer buffer = helper.Lex();
  290. CARBON_CHECK(!buffer.has_errors());
  291. }
  292. state.SetBytesProcessed(state.iterations() * source.size());
  293. state.counters["tokens_per_second"] = benchmark::Counter(
  294. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  295. }
  296. BENCHMARK(BM_ValidKeywords);
  297. template <int MinLength, int MaxLength, bool Uniform>
  298. void BM_ValidIdentifiers(benchmark::State& state) {
  299. std::string source = RandomIdentifierSeq<MinLength, MaxLength, Uniform>();
  300. LexerBenchHelper helper(source);
  301. for (auto _ : state) {
  302. TokenizedBuffer buffer = helper.Lex();
  303. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  304. }
  305. state.SetBytesProcessed(state.iterations() * source.size());
  306. state.counters["tokens_per_second"] = benchmark::Counter(
  307. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  308. }
  309. // Benchmark the non-uniform distribution we observe in C++ code.
  310. BENCHMARK(BM_ValidIdentifiers<1, 64, /*Uniform=*/false>);
  311. // Also benchmark a few uniform distribution ranges of identifier widths to
  312. // cover different patterns that emerge with small, medium, and longer
  313. // identifiers.
  314. BENCHMARK(BM_ValidIdentifiers<1, 1, /*Uniform=*/true>);
  315. BENCHMARK(BM_ValidIdentifiers<3, 5, /*Uniform=*/true>);
  316. BENCHMARK(BM_ValidIdentifiers<3, 16, /*Uniform=*/true>);
  317. BENCHMARK(BM_ValidIdentifiers<12, 64, /*Uniform=*/true>);
  318. void BM_ValidMix(benchmark::State& state) {
  319. int symbol_percent = state.range(0);
  320. int keyword_percent = state.range(1);
  321. std::string source = RandomMixedSeq(symbol_percent, keyword_percent);
  322. LexerBenchHelper helper(source);
  323. for (auto _ : state) {
  324. TokenizedBuffer buffer = helper.Lex();
  325. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  326. // hit errors that would skew the benchmark results.
  327. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  328. }
  329. state.SetBytesProcessed(state.iterations() * source.size());
  330. state.counters["tokens_per_second"] = benchmark::Counter(
  331. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  332. }
  333. // The distributions between symbols, keywords, and identifiers here are
  334. // guesses. Eventually, we should collect more data to help tune these, but
  335. // hopefully the performance isn't too sensitive and we can just cover a wide
  336. // range here.
  337. BENCHMARK(BM_ValidMix)
  338. ->Args({10, 40})
  339. ->Args({25, 30})
  340. ->Args({50, 20})
  341. ->Args({75, 10});
  342. } // namespace
  343. } // namespace Carbon::Testing