tokenized_buffer_benchmark.cpp 15 KB

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