map_benchmark.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 <type_traits>
  6. #include "absl/container/flat_hash_map.h"
  7. #include "common/map.h"
  8. #include "common/raw_hashtable_benchmark_helpers.h"
  9. #include "llvm/ADT/DenseMap.h"
  10. namespace Carbon {
  11. namespace {
  12. using RawHashtable::CarbonHashDI;
  13. using RawHashtable::GetKeysAndHitKeys;
  14. using RawHashtable::GetKeysAndMissKeys;
  15. using RawHashtable::HitArgs;
  16. using RawHashtable::SizeArgs;
  17. using RawHashtable::ValueToBool;
  18. // Helpers to synthesize some value of one of the three types we use as value
  19. // types.
  20. template <typename T>
  21. auto MakeValue() -> T {
  22. if constexpr (std::is_same_v<T, llvm::StringRef>) {
  23. return "abc";
  24. } else if constexpr (std::is_pointer_v<T>) {
  25. static std::remove_pointer_t<T> x;
  26. return &x;
  27. } else {
  28. return 42;
  29. }
  30. }
  31. template <typename T>
  32. auto MakeValue2() -> T {
  33. if constexpr (std::is_same_v<T, llvm::StringRef>) {
  34. return "qux";
  35. } else if constexpr (std::is_pointer_v<T>) {
  36. static std::remove_pointer_t<T> y;
  37. return &y;
  38. } else {
  39. return 7;
  40. }
  41. }
  42. template <typename MapT>
  43. struct IsCarbonMapImpl : std::false_type {};
  44. template <typename KT, typename VT, int MinSmallSize>
  45. struct IsCarbonMapImpl<Map<KT, VT, MinSmallSize>> : std::true_type {};
  46. template <typename MapT>
  47. static constexpr bool IsCarbonMap = IsCarbonMapImpl<MapT>::value;
  48. // A wrapper around various map types that we specialize to implement a common
  49. // API used in the benchmarks for various different map data structures that
  50. // support different APIs. The primary template assumes a roughly
  51. // `std::unordered_map` API design, and types with a different API design are
  52. // supported through specializations.
  53. template <typename MapT>
  54. struct MapWrapperImpl {
  55. using KeyT = typename MapT::key_type;
  56. using ValueT = typename MapT::mapped_type;
  57. MapT m;
  58. auto BenchContains(KeyT k) -> bool { return m.find(k) != m.end(); }
  59. auto BenchLookup(KeyT k) -> bool {
  60. auto it = m.find(k);
  61. if (it == m.end()) {
  62. return false;
  63. }
  64. return ValueToBool(it->second);
  65. }
  66. auto BenchInsert(KeyT k, ValueT v) -> bool {
  67. auto result = m.insert({k, v});
  68. return result.second;
  69. }
  70. auto BenchUpdate(KeyT k, ValueT v) -> bool {
  71. auto result = m.insert({k, v});
  72. result.first->second = v;
  73. return result.second;
  74. }
  75. auto BenchErase(KeyT k) -> bool { return m.erase(k) != 0; }
  76. };
  77. // Explicit (partial) specialization for the Carbon map type that uses its
  78. // different API design.
  79. template <typename KT, typename VT, int MinSmallSize>
  80. struct MapWrapperImpl<Map<KT, VT, MinSmallSize>> {
  81. using MapT = Map<KT, VT, MinSmallSize>;
  82. using KeyT = KT;
  83. using ValueT = VT;
  84. MapT m;
  85. auto BenchContains(KeyT k) -> bool { return m.Contains(k); }
  86. auto BenchLookup(KeyT k) -> bool {
  87. auto result = m.Lookup(k);
  88. if (!result) {
  89. return false;
  90. }
  91. return ValueToBool(result.value());
  92. }
  93. auto BenchInsert(KeyT k, ValueT v) -> bool {
  94. auto result = m.Insert(k, v);
  95. return result.is_inserted();
  96. }
  97. auto BenchUpdate(KeyT k, ValueT v) -> bool {
  98. auto result = m.Update(k, v);
  99. return result.is_inserted();
  100. }
  101. auto BenchErase(KeyT k) -> bool { return m.Erase(k); }
  102. };
  103. // Provide a way to override the Carbon Map specific benchmark runs with another
  104. // hashtable implementation. When building, you can use one of these enum names
  105. // in a macro define such as `-DCARBON_MAP_BENCH_OVERRIDE=Name` in order to
  106. // trigger a specific override for the `Map` type benchmarks. This is used to
  107. // get before/after runs that compare the performance of Carbon's Map versus
  108. // other implementations.
  109. enum class MapOverride : uint8_t {
  110. None,
  111. Abseil,
  112. LLVM,
  113. LLVMAndCarbonHash,
  114. };
  115. #ifndef CARBON_MAP_BENCH_OVERRIDE
  116. #define CARBON_MAP_BENCH_OVERRIDE None
  117. #endif
  118. template <typename MapT, MapOverride Override>
  119. struct MapWrapperOverride : MapWrapperImpl<MapT> {};
  120. template <typename KeyT, typename ValueT, int MinSmallSize>
  121. struct MapWrapperOverride<Map<KeyT, ValueT, MinSmallSize>, MapOverride::Abseil>
  122. : MapWrapperImpl<absl::flat_hash_map<KeyT, ValueT>> {};
  123. template <typename KeyT, typename ValueT, int MinSmallSize>
  124. struct MapWrapperOverride<Map<KeyT, ValueT, MinSmallSize>, MapOverride::LLVM>
  125. : MapWrapperImpl<llvm::DenseMap<KeyT, ValueT>> {};
  126. template <typename KeyT, typename ValueT, int MinSmallSize>
  127. struct MapWrapperOverride<Map<KeyT, ValueT, MinSmallSize>,
  128. MapOverride::LLVMAndCarbonHash>
  129. : MapWrapperImpl<llvm::DenseMap<KeyT, ValueT, CarbonHashDI<KeyT>>> {};
  130. template <typename MapT>
  131. using MapWrapper =
  132. MapWrapperOverride<MapT, MapOverride::CARBON_MAP_BENCH_OVERRIDE>;
  133. // NOLINTBEGIN(bugprone-macro-parentheses): Parentheses are incorrect here.
  134. #define MAP_BENCHMARK_ONE_OP_SIZE(NAME, APPLY, KT, VT) \
  135. BENCHMARK(NAME<Map<KT, VT>>)->Apply(APPLY); \
  136. BENCHMARK(NAME<absl::flat_hash_map<KT, VT>>)->Apply(APPLY); \
  137. BENCHMARK(NAME<llvm::DenseMap<KT, VT>>)->Apply(APPLY); \
  138. BENCHMARK(NAME<llvm::DenseMap<KT, VT, CarbonHashDI<KT>>>)->Apply(APPLY)
  139. // NOLINTEND(bugprone-macro-parentheses)
  140. #define MAP_BENCHMARK_ONE_OP(NAME, APPLY) \
  141. MAP_BENCHMARK_ONE_OP_SIZE(NAME, APPLY, int, int); \
  142. MAP_BENCHMARK_ONE_OP_SIZE(NAME, APPLY, int*, int*); \
  143. MAP_BENCHMARK_ONE_OP_SIZE(NAME, APPLY, int, llvm::StringRef); \
  144. MAP_BENCHMARK_ONE_OP_SIZE(NAME, APPLY, llvm::StringRef, int)
  145. // Benchmark the minimal latency of checking if a key is contained within a map,
  146. // when it *is* definitely in that map. Because this is only really measuring
  147. // the *minimal* latency, it is more similar to a throughput benchmark.
  148. //
  149. // While this is structured to observe the latency of testing for presence of a
  150. // key, it is important to understand the reality of what this measures. Because
  151. // the boolean result testing for whether a key is in a map is fundamentally
  152. // provided not by accessing some data, but by branching on data to a control
  153. // flow path which sets the boolean to `true` or `false`, the result can be
  154. // speculatively provided based on predicting the conditional branch without
  155. // waiting for the results of the comparison to become available. And because
  156. // this is a small operation and we arrange for all the candidate keys to be
  157. // present, that branch *should* be predicted extremely well. The result is that
  158. // this measures the un-speculated latency of testing for presence which should
  159. // be small or zero. Which is why this is ultimately more similar to a
  160. // throughput benchmark.
  161. //
  162. // Because of these measurement oddities, the specific measurements here may not
  163. // be very interesting for predicting real-world performance in any way, but
  164. // they are useful for comparing how 'cheap' the operation is across changes to
  165. // the data structure or between similar data structures with similar
  166. // properties.
  167. template <typename MapT>
  168. static void BM_MapContainsHit(benchmark::State& state) {
  169. using MapWrapperT = MapWrapper<MapT>;
  170. using KT = typename MapWrapperT::KeyT;
  171. using VT = typename MapWrapperT::ValueT;
  172. MapWrapperT m;
  173. auto [keys, lookup_keys] =
  174. GetKeysAndHitKeys<KT>(state.range(0), state.range(1));
  175. for (auto k : keys) {
  176. m.BenchInsert(k, MakeValue<VT>());
  177. }
  178. ssize_t lookup_keys_size = lookup_keys.size();
  179. while (state.KeepRunningBatch(lookup_keys_size)) {
  180. for (ssize_t i = 0; i < lookup_keys_size;) {
  181. // We block optimizing `i` as that has proven both more effective at
  182. // blocking the loop from being optimized away and avoiding disruption of
  183. // the generated code that we're benchmarking.
  184. benchmark::DoNotOptimize(i);
  185. bool result = m.BenchContains(lookup_keys[i]);
  186. CARBON_DCHECK(result);
  187. // We use the lookup success to step through keys, establishing a
  188. // dependency between each lookup. This doesn't fully allow us to measure
  189. // latency rather than throughput, as noted above.
  190. i += static_cast<ssize_t>(result);
  191. }
  192. }
  193. }
  194. MAP_BENCHMARK_ONE_OP(BM_MapContainsHit, HitArgs);
  195. // Similar to `BM_MapContainsHit`, while this is structured as a latency
  196. // benchmark, the critical path is expected to be well predicted and so it
  197. // should turn into something closer to a throughput benchmark.
  198. template <typename MapT>
  199. static void BM_MapContainsMiss(benchmark::State& state) {
  200. using MapWrapperT = MapWrapper<MapT>;
  201. using KT = typename MapWrapperT::KeyT;
  202. using VT = typename MapWrapperT::ValueT;
  203. MapWrapperT m;
  204. auto [keys, lookup_keys] = GetKeysAndMissKeys<KT>(state.range(0));
  205. for (auto k : keys) {
  206. m.BenchInsert(k, MakeValue<VT>());
  207. }
  208. ssize_t lookup_keys_size = lookup_keys.size();
  209. while (state.KeepRunningBatch(lookup_keys_size)) {
  210. for (ssize_t i = 0; i < lookup_keys_size;) {
  211. benchmark::DoNotOptimize(i);
  212. bool result = m.BenchContains(lookup_keys[i]);
  213. CARBON_DCHECK(!result);
  214. i += static_cast<ssize_t>(!result);
  215. }
  216. }
  217. }
  218. MAP_BENCHMARK_ONE_OP(BM_MapContainsMiss, SizeArgs);
  219. // This is a genuine latency benchmark. We lookup a key in the hashtable and use
  220. // the value associated with that key in the critical path of loading the next
  221. // iteration's key. We still ensure the keys are always present, and so we
  222. // generally expect the data structure branches to be well predicted. But we
  223. // vary the keys aggressively to avoid any prediction artifacts from repeatedly
  224. // examining the same key.
  225. //
  226. // This latency can be very helpful for understanding a range of data structure
  227. // behaviors:
  228. // - Many users of hashtables are directly dependent on the latency of this
  229. // operation, and this micro-benchmark will reflect the expected latency for
  230. // them.
  231. // - Showing how latency varies across different sizes of table and different
  232. // fractions of the table being accessed (and thus needing space in the
  233. // cache).
  234. //
  235. // However, it remains an ultimately synthetic and unrepresentative benchmark.
  236. // It should primarily be used to understand the relative cost of these
  237. // operations between versions of the data structure or between related data
  238. // structures.
  239. //
  240. // We vary both the number of entries in the table and the number of distinct
  241. // keys used when doing lookups. As the table becomes large, the latter dictates
  242. // the fraction of the table that will be accessed and thus the working set size
  243. // of the benchmark. Querying the same small number of keys in even a large
  244. // table doesn't actually encounter any cache pressure, so only a few of these
  245. // benchmarks will show any effects of the caching subsystem.
  246. template <typename MapT>
  247. static void BM_MapLookupHit(benchmark::State& state) {
  248. using MapWrapperT = MapWrapper<MapT>;
  249. using KT = typename MapWrapperT::KeyT;
  250. using VT = typename MapWrapperT::ValueT;
  251. MapWrapperT m;
  252. auto [keys, lookup_keys] =
  253. GetKeysAndHitKeys<KT>(state.range(0), state.range(1));
  254. for (auto k : keys) {
  255. m.BenchInsert(k, MakeValue<VT>());
  256. }
  257. ssize_t lookup_keys_size = lookup_keys.size();
  258. while (state.KeepRunningBatch(lookup_keys_size)) {
  259. for (ssize_t i = 0; i < lookup_keys_size;) {
  260. benchmark::DoNotOptimize(i);
  261. bool result = m.BenchLookup(lookup_keys[i]);
  262. CARBON_DCHECK(result);
  263. i += static_cast<ssize_t>(result);
  264. }
  265. }
  266. }
  267. MAP_BENCHMARK_ONE_OP(BM_MapLookupHit, HitArgs);
  268. // This is an update throughput benchmark in practice. While whether the key was
  269. // a hit is kept in the critical path, we only use keys that are hits and so
  270. // expect that to be fully predicted and speculated.
  271. //
  272. // However, we expect this fairly closely matches how user code interacts with
  273. // an update-style API. It will have some conditional testing (even if just an
  274. // assert) on whether the key was a hit and otherwise continue executing. As a
  275. // consequence the actual update is expected to not be in a meaningful critical
  276. // path.
  277. //
  278. // This still provides a basic way to measure the cost of this operation,
  279. // especially when comparing between implementations or across different hash
  280. // tables.
  281. template <typename MapT>
  282. static void BM_MapUpdateHit(benchmark::State& state) {
  283. using MapWrapperT = MapWrapper<MapT>;
  284. using KT = typename MapWrapperT::KeyT;
  285. using VT = typename MapWrapperT::ValueT;
  286. MapWrapperT m;
  287. auto [keys, lookup_keys] =
  288. GetKeysAndHitKeys<KT>(state.range(0), state.range(1));
  289. for (auto k : keys) {
  290. m.BenchInsert(k, MakeValue<VT>());
  291. }
  292. ssize_t lookup_keys_size = lookup_keys.size();
  293. while (state.KeepRunningBatch(lookup_keys_size)) {
  294. for (ssize_t i = 0; i < lookup_keys_size; ++i) {
  295. benchmark::DoNotOptimize(i);
  296. bool inserted = m.BenchUpdate(lookup_keys[i], MakeValue2<VT>());
  297. CARBON_DCHECK(!inserted);
  298. }
  299. }
  300. }
  301. MAP_BENCHMARK_ONE_OP(BM_MapUpdateHit, HitArgs);
  302. // First erase and then insert the key. The code path will always be the same
  303. // here and so we expect this to largely be a throughput benchmark because of
  304. // branch prediction and speculative execution.
  305. //
  306. // We don't expect erase followed by insertion to be a common user code
  307. // sequence, but we don't have a good way of benchmarking either erase or insert
  308. // in isolation -- each would change the size of the table and thus the next
  309. // iteration's benchmark. And if we try to correct the table size outside of the
  310. // timed region, we end up trying to exclude too fine grained of a region from
  311. // timers to get good measurement data.
  312. //
  313. // Our solution is to benchmark both erase and insertion back to back. We can
  314. // then get a good profile of the code sequence of each, and at least measure
  315. // the sum cost of these reliably. Careful profiling can help attribute that
  316. // cost between erase and insert in order to understand which of the two
  317. // operations is contributing most to any performance artifacts observed.
  318. template <typename MapT>
  319. static void BM_MapEraseUpdateHit(benchmark::State& state) {
  320. using MapWrapperT = MapWrapper<MapT>;
  321. using KT = typename MapWrapperT::KeyT;
  322. using VT = typename MapWrapperT::ValueT;
  323. MapWrapperT m;
  324. auto [keys, lookup_keys] =
  325. GetKeysAndHitKeys<KT>(state.range(0), state.range(1));
  326. for (auto k : keys) {
  327. m.BenchInsert(k, MakeValue<VT>());
  328. }
  329. ssize_t lookup_keys_size = lookup_keys.size();
  330. while (state.KeepRunningBatch(lookup_keys_size)) {
  331. for (ssize_t i = 0; i < lookup_keys_size; ++i) {
  332. benchmark::DoNotOptimize(i);
  333. m.BenchErase(lookup_keys[i]);
  334. benchmark::ClobberMemory();
  335. bool inserted = m.BenchUpdate(lookup_keys[i], MakeValue2<VT>());
  336. CARBON_DCHECK(inserted);
  337. }
  338. }
  339. }
  340. MAP_BENCHMARK_ONE_OP(BM_MapEraseUpdateHit, HitArgs);
  341. // NOLINTBEGIN(bugprone-macro-parentheses): Parentheses are incorrect here.
  342. #define MAP_BENCHMARK_OP_SEQ_SIZE(NAME, KT, VT) \
  343. BENCHMARK(NAME<Map<KT, VT>>)->Apply(SizeArgs); \
  344. BENCHMARK(NAME<absl::flat_hash_map<KT, VT>>)->Apply(SizeArgs); \
  345. BENCHMARK(NAME<llvm::DenseMap<KT, VT>>)->Apply(APPLY); \
  346. BENCHMARK(NAME<llvm::DenseMap<KT, VT, CarbonHashDI<KT>>>)->Apply(SizeArgs)
  347. // NOLINTEND(bugprone-macro-parentheses)
  348. #define MAP_BENCHMARK_OP_SEQ(NAME) \
  349. MAP_BENCHMARK_OP_SEQ_SIZE(NAME, int, int); \
  350. MAP_BENCHMARK_OP_SEQ_SIZE(NAME, int*, int*); \
  351. MAP_BENCHMARK_OP_SEQ_SIZE(NAME, int, llvm::StringRef); \
  352. MAP_BENCHMARK_OP_SEQ_SIZE(NAME, llvm::StringRef, int)
  353. // This is an interesting, somewhat specialized benchmark that measures the cost
  354. // of inserting a sequence of key/value pairs into a table with no collisions up
  355. // to some size and then inserting a colliding key and throwing away the table.
  356. //
  357. // This can give an idea of the cost of building up a map of a particular size,
  358. // but without actually using it. Or of algorithms like cycle-detection which
  359. // for some reason need an associative container.
  360. //
  361. // It also covers both the insert-into-an-empty-slot code path that isn't
  362. // covered elsewhere, and the code path for growing a table to a larger size.
  363. //
  364. // Because this benchmark operates on whole maps, we also compute the number of
  365. // probed keys for Carbon's set as that is both a general reflection of the
  366. // efficacy of the underlying hash function, and a direct factor that drives the
  367. // cost of these operations.
  368. template <typename MapT>
  369. static void BM_MapInsertSeq(benchmark::State& state) {
  370. using MapWrapperT = MapWrapper<MapT>;
  371. using KT = typename MapWrapperT::KeyT;
  372. using VT = typename MapWrapperT::ValueT;
  373. constexpr ssize_t LookupKeysSize = 1 << 8;
  374. auto [keys, lookup_keys] =
  375. GetKeysAndHitKeys<KT>(state.range(0), LookupKeysSize);
  376. // Note that we don't force batches that use all the lookup keys because
  377. // there's no difference in cache usage by covering all the different lookup
  378. // keys.
  379. ssize_t i = 0;
  380. for (auto _ : state) {
  381. benchmark::DoNotOptimize(i);
  382. MapWrapperT m;
  383. for (auto k : keys) {
  384. bool inserted = m.BenchInsert(k, MakeValue<VT>());
  385. CARBON_DCHECK(inserted) << "Must be a successful insert!";
  386. }
  387. // Now insert a final random repeated key.
  388. bool inserted = m.BenchInsert(lookup_keys[i], MakeValue2<VT>());
  389. CARBON_DCHECK(!inserted) << "Must already be in the map!";
  390. // Rotate through the shuffled keys.
  391. i = (i + static_cast<ssize_t>(!inserted)) & (LookupKeysSize - 1);
  392. }
  393. // It can be easier in some cases to think of this as a key-throughput rate of
  394. // insertion rather than the latency of inserting N keys, so construct the
  395. // rate counter as well.
  396. state.counters["KeyRate"] = benchmark::Counter(
  397. keys.size(), benchmark::Counter::kIsIterationInvariantRate);
  398. // Report some extra statistics about the Carbon type.
  399. if constexpr (IsCarbonMap<MapT>) {
  400. // Re-build a map outside of the timing loop to look at the statistics
  401. // rather than the timing.
  402. MapT m;
  403. for (auto k : keys) {
  404. bool inserted = m.Insert(k, MakeValue<VT>()).is_inserted();
  405. CARBON_DCHECK(inserted) << "Must be a successful insert!";
  406. }
  407. // While this count is "iteration invariant" (it should be exactly the same
  408. // for every iteration as the set of keys is the same), we don't use that
  409. // because it will scale this by the number of iterations. We want to
  410. // display the probe count of this benchmark *parameter*, not the probe
  411. // count that resulted from the number of iterations. That means we use the
  412. // normal counter API without flags.
  413. state.counters["Probed"] = m.CountProbedKeys();
  414. // Uncomment this call to print out statistics about the index-collisions
  415. // among these keys for debugging:
  416. //
  417. // RawHashtable::DumpHashStatistics(keys);
  418. }
  419. }
  420. MAP_BENCHMARK_ONE_OP(BM_MapInsertSeq, SizeArgs);
  421. } // namespace
  422. } // namespace Carbon