set_benchmark.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 "absl/container/flat_hash_set.h"
  6. #include "common/raw_hashtable_benchmark_helpers.h"
  7. #include "common/set.h"
  8. #include "llvm/ADT/DenseSet.h"
  9. namespace Carbon {
  10. namespace {
  11. using RawHashtable::CarbonHashDI;
  12. using RawHashtable::GetKeysAndHitKeys;
  13. using RawHashtable::GetKeysAndMissKeys;
  14. using RawHashtable::HitArgs;
  15. using RawHashtable::ReportTableMetrics;
  16. using RawHashtable::SizeArgs;
  17. using RawHashtable::ValueToBool;
  18. template <typename SetT>
  19. struct IsCarbonSetImpl : std::false_type {};
  20. template <typename KT, int MinSmallSize>
  21. struct IsCarbonSetImpl<Set<KT, MinSmallSize>> : std::true_type {};
  22. template <typename SetT>
  23. static constexpr bool IsCarbonSet = IsCarbonSetImpl<SetT>::value;
  24. // A wrapper around various set types that we specialize to implement a common
  25. // API used in the benchmarks for various different map data structures that
  26. // support different APIs. The primary template assumes a roughly
  27. // `std::unordered_set` API design, and types with a different API design are
  28. // supported through specializations.
  29. template <typename SetT>
  30. struct SetWrapperImpl {
  31. using KeyT = typename SetT::key_type;
  32. SetT s;
  33. auto BenchContains(KeyT k) -> bool { return s.find(k) != s.end(); }
  34. auto BenchLookup(KeyT k) -> bool {
  35. auto it = s.find(k);
  36. if (it == s.end()) {
  37. return false;
  38. }
  39. // We expect keys to always convert to `true` so directly return that here.
  40. return ValueToBool(*it);
  41. }
  42. auto BenchInsert(KeyT k) -> bool {
  43. auto result = s.insert(k);
  44. return result.second;
  45. }
  46. auto BenchErase(KeyT k) -> bool { return s.erase(k) != 0; }
  47. };
  48. // Explicit (partial) specialization for the Carbon map type that uses its
  49. // different API design.
  50. template <typename KT, int MinSmallSize>
  51. struct SetWrapperImpl<Set<KT, MinSmallSize>> {
  52. using SetT = Set<KT, MinSmallSize>;
  53. using KeyT = KT;
  54. SetT s;
  55. auto BenchContains(KeyT k) -> bool { return s.Contains(k); }
  56. auto BenchLookup(KeyT k) -> bool {
  57. auto result = s.Lookup(k);
  58. if (!result) {
  59. return false;
  60. }
  61. return ValueToBool(result.key());
  62. }
  63. auto BenchInsert(KeyT k) -> bool {
  64. auto result = s.Insert(k);
  65. return result.is_inserted();
  66. }
  67. auto BenchErase(KeyT k) -> bool { return s.Erase(k); }
  68. };
  69. // Provide a way to override the Carbon Set specific benchmark runs with another
  70. // hashtable implementation. When building, you can use one of these enum names
  71. // in a macro define such as `-DCARBON_SET_BENCH_OVERRIDE=Name` in order to
  72. // trigger a specific override for the `Set` type benchmarks. This is used to
  73. // get before/after runs that compare the performance of Carbon's Set versus
  74. // other implementations.
  75. enum class SetOverride : uint8_t {
  76. Abseil,
  77. LLVM,
  78. LLVMAndCarbonHash,
  79. };
  80. template <typename SetT, SetOverride Override>
  81. struct SetWrapperOverride : SetWrapperImpl<SetT> {};
  82. template <typename KeyT, int MinSmallSize>
  83. struct SetWrapperOverride<Set<KeyT, MinSmallSize>, SetOverride::Abseil>
  84. : SetWrapperImpl<absl::flat_hash_set<KeyT>> {};
  85. template <typename KeyT, int MinSmallSize>
  86. struct SetWrapperOverride<Set<KeyT, MinSmallSize>, SetOverride::LLVM>
  87. : SetWrapperImpl<llvm::DenseSet<KeyT>> {};
  88. template <typename KeyT, int MinSmallSize>
  89. struct SetWrapperOverride<Set<KeyT, MinSmallSize>,
  90. SetOverride::LLVMAndCarbonHash>
  91. : SetWrapperImpl<llvm::DenseSet<KeyT, CarbonHashDI<KeyT>>> {};
  92. #ifndef CARBON_SET_BENCH_OVERRIDE
  93. template <typename SetT>
  94. using SetWrapper = SetWrapperImpl<SetT>;
  95. #else
  96. template <typename SetT>
  97. using SetWrapper =
  98. SetWrapperOverride<SetT, SetOverride::CARBON_SET_BENCH_OVERRIDE>;
  99. #endif
  100. // NOLINTBEGIN(bugprone-macro-parentheses): Parentheses are incorrect here.
  101. #define MAP_BENCHMARK_ONE_OP_SIZE(NAME, APPLY, KT) \
  102. BENCHMARK(NAME<Set<KT>>)->Apply(APPLY); \
  103. BENCHMARK(NAME<absl::flat_hash_set<KT>>)->Apply(APPLY); \
  104. BENCHMARK(NAME<llvm::DenseSet<KT>>)->Apply(APPLY); \
  105. BENCHMARK(NAME<llvm::DenseSet<KT, CarbonHashDI<KT>>>)->Apply(APPLY)
  106. // NOLINTEND(bugprone-macro-parentheses)
  107. #define MAP_BENCHMARK_ONE_OP(NAME, APPLY) \
  108. MAP_BENCHMARK_ONE_OP_SIZE(NAME, APPLY, int); \
  109. MAP_BENCHMARK_ONE_OP_SIZE(NAME, APPLY, int*); \
  110. MAP_BENCHMARK_ONE_OP_SIZE(NAME, APPLY, llvm::StringRef)
  111. // Benchmark the "latency" of testing for a key in a set. This always tests with
  112. // a key that is found.
  113. //
  114. // However, because the key is always found and because the test ultimately
  115. // involves conditional control flow that can be predicted, we expect modern
  116. // CPUs to perfectly predict the control flow here and turn the measurement from
  117. // one iteration to the next into a throughput measurement rather than a real
  118. // latency measurement.
  119. //
  120. // However, this does represent a particularly common way in which a set data
  121. // structure is accessed. The numbers should just be carefully interpreted in
  122. // the context of being more a reflection of reciprocal throughput than actual
  123. // latency. See the `Lookup` benchmarks for a genuine latency measure with its
  124. // own caveats.
  125. //
  126. // However, this does still show some interesting caching effects when querying
  127. // large fractions of large tables, and can give a sense of the inescapable
  128. // magnitude of these effects even when there is a great deal of prediction and
  129. // speculative execution to hide memory access latency.
  130. template <typename SetT>
  131. static void BM_SetContainsHitPtr(benchmark::State& state) {
  132. using SetWrapperT = SetWrapper<SetT>;
  133. using KT = typename SetWrapperT::KeyT;
  134. SetWrapperT s;
  135. auto [keys, lookup_keys] =
  136. GetKeysAndHitKeys<KT>(state.range(0), state.range(1));
  137. for (auto k : keys) {
  138. s.BenchInsert(k);
  139. }
  140. ssize_t lookup_keys_size = lookup_keys.size();
  141. while (state.KeepRunningBatch(lookup_keys_size)) {
  142. for (ssize_t i = 0; i < lookup_keys_size;) {
  143. // We block optimizing `i` as that has proven both more effective at
  144. // blocking the loop from being optimized away and avoiding disruption of
  145. // the generated code that we're benchmarking.
  146. benchmark::DoNotOptimize(i);
  147. bool result = s.BenchContains(lookup_keys[i]);
  148. CARBON_DCHECK(result);
  149. // We use the lookup success to step through keys, establishing a
  150. // dependency between each lookup. This doesn't fully allow us to measure
  151. // latency rather than throughput, as noted above.
  152. i += static_cast<ssize_t>(result);
  153. }
  154. }
  155. }
  156. MAP_BENCHMARK_ONE_OP(BM_SetContainsHitPtr, HitArgs);
  157. // Benchmark the "latency" (but more likely the reciprocal throughput, see
  158. // comment above) of testing for a key in the set that is *not* present.
  159. template <typename SetT>
  160. static void BM_SetContainsMissPtr(benchmark::State& state) {
  161. using SetWrapperT = SetWrapper<SetT>;
  162. using KT = typename SetWrapperT::KeyT;
  163. SetWrapperT s;
  164. auto [keys, lookup_keys] = GetKeysAndMissKeys<KT>(state.range(0));
  165. for (auto k : keys) {
  166. s.BenchInsert(k);
  167. }
  168. ssize_t lookup_keys_size = lookup_keys.size();
  169. while (state.KeepRunningBatch(lookup_keys_size)) {
  170. for (ssize_t i = 0; i < lookup_keys_size;) {
  171. benchmark::DoNotOptimize(i);
  172. bool result = s.BenchContains(lookup_keys[i]);
  173. CARBON_DCHECK(!result);
  174. i += static_cast<ssize_t>(!result);
  175. }
  176. }
  177. }
  178. MAP_BENCHMARK_ONE_OP(BM_SetContainsMissPtr, SizeArgs);
  179. // A somewhat contrived latency test for the lookup code path.
  180. //
  181. // While lookups into a set are often (but not always) simply used to influence
  182. // control flow, that style of access produces difficult to evaluate benchmark
  183. // results (see the comments on the `Contains` benchmarks above).
  184. //
  185. // So here we actually access the key in the set and convert that key's value to
  186. // a boolean on the critical path of each iteration. This lets us have a genuine
  187. // latency benchmark of looking up a key in the set, at the expense of being
  188. // somewhat contrived. That said, for usage where the key object is queried or
  189. // operated on in some way once looked up in the set, this will be fairly
  190. // representative of the latency cost from the data structure.
  191. template <typename SetT>
  192. static void BM_SetLookupHitPtr(benchmark::State& state) {
  193. using SetWrapperT = SetWrapper<SetT>;
  194. using KT = typename SetWrapperT::KeyT;
  195. SetWrapperT s;
  196. auto [keys, lookup_keys] =
  197. GetKeysAndHitKeys<KT>(state.range(0), state.range(1));
  198. for (auto k : keys) {
  199. s.BenchInsert(k);
  200. }
  201. ssize_t lookup_keys_size = lookup_keys.size();
  202. while (state.KeepRunningBatch(lookup_keys_size)) {
  203. for (ssize_t i = 0; i < lookup_keys_size;) {
  204. benchmark::DoNotOptimize(i);
  205. bool result = s.BenchLookup(lookup_keys[i]);
  206. CARBON_DCHECK(result);
  207. i += static_cast<ssize_t>(result);
  208. }
  209. }
  210. }
  211. MAP_BENCHMARK_ONE_OP(BM_SetLookupHitPtr, HitArgs);
  212. // First erase and then insert the key. The code path will always be the same
  213. // here and so we expect this to largely be a throughput benchmark because of
  214. // branch prediction and speculative execution.
  215. //
  216. // We don't expect erase followed by insertion to be a common user code
  217. // sequence, but we don't have a good way of benchmarking either erase or insert
  218. // in isolation -- each would change the size of the table and thus the next
  219. // iteration's benchmark. And if we try to correct the table size outside of the
  220. // timed region, we end up trying to exclude too fine grained of a region from
  221. // timers to get good measurement data.
  222. //
  223. // Our solution is to benchmark both erase and insertion back to back. We can
  224. // then get a good profile of the code sequence of each, and at least measure
  225. // the sum cost of these reliably. Careful profiling can help attribute that
  226. // cost between erase and insert in order to understand which of the two
  227. // operations is contributing most to any performance artifacts observed.
  228. template <typename SetT>
  229. static void BM_SetEraseInsertHitPtr(benchmark::State& state) {
  230. using SetWrapperT = SetWrapper<SetT>;
  231. using KT = typename SetWrapperT::KeyT;
  232. SetWrapperT s;
  233. auto [keys, lookup_keys] =
  234. GetKeysAndHitKeys<KT>(state.range(0), state.range(1));
  235. for (auto k : keys) {
  236. s.BenchInsert(k);
  237. }
  238. ssize_t lookup_keys_size = lookup_keys.size();
  239. while (state.KeepRunningBatch(lookup_keys_size)) {
  240. for (ssize_t i = 0; i < lookup_keys_size;) {
  241. benchmark::DoNotOptimize(i);
  242. s.BenchErase(lookup_keys[i]);
  243. benchmark::ClobberMemory();
  244. bool inserted = s.BenchInsert(lookup_keys[i]);
  245. CARBON_DCHECK(inserted);
  246. i += static_cast<ssize_t>(inserted);
  247. }
  248. }
  249. }
  250. MAP_BENCHMARK_ONE_OP(BM_SetEraseInsertHitPtr, HitArgs);
  251. // NOLINTBEGIN(bugprone-macro-parentheses): Parentheses are incorrect here.
  252. #define MAP_BENCHMARK_OP_SEQ_SIZE(NAME, KT) \
  253. BENCHMARK(NAME<Set<KT>>)->Apply(SizeArgs); \
  254. BENCHMARK(NAME<absl::flat_hash_set<KT>>)->Apply(SizeArgs); \
  255. BENCHMARK(NAME<llvm::DenseSet<KT>>)->Apply(SizeArgs); \
  256. BENCHMARK(NAME<llvm::DenseSet<KT, CarbonHashDI<KT>>>)->Apply(SizeArgs)
  257. // NOLINTEND(bugprone-macro-parentheses)
  258. #define MAP_BENCHMARK_OP_SEQ(NAME) \
  259. MAP_BENCHMARK_OP_SEQ_SIZE(NAME, int); \
  260. MAP_BENCHMARK_OP_SEQ_SIZE(NAME, int*); \
  261. MAP_BENCHMARK_OP_SEQ_SIZE(NAME, llvm::StringRef)
  262. // This is an interesting, somewhat specialized benchmark that measures the cost
  263. // of inserting a sequence of keys into a set up to some size and then inserting
  264. // a colliding key and throwing away the set.
  265. //
  266. // This is an especially important usage pattern for sets as a large number of
  267. // algorithms essentially look like this, such as collision detection, cycle
  268. // detection, de-duplication, etc.
  269. //
  270. // It also covers both the insert-into-an-empty-slot code path that isn't
  271. // covered elsewhere, and the code path for growing a table to a larger size.
  272. //
  273. // This is the second most important aspect of expected set usage after testing
  274. // for presence. It also nicely lends itself to a single benchmark that covers
  275. // the total cost of this usage pattern.
  276. //
  277. // Because this benchmark operates on whole sets, we also compute the number of
  278. // probed keys for Carbon's set as that is both a general reflection of the
  279. // efficacy of the underlying hash function, and a direct factor that drives the
  280. // cost of these operations.
  281. template <typename SetT>
  282. static void BM_SetInsertSeq(benchmark::State& state) {
  283. using SetWrapperT = SetWrapper<SetT>;
  284. using KT = typename SetWrapperT::KeyT;
  285. constexpr ssize_t LookupKeysSize = 1 << 8;
  286. auto [keys, lookup_keys] =
  287. GetKeysAndHitKeys<KT>(state.range(0), LookupKeysSize);
  288. // Now build a large shuffled set of keys (with duplicates) we'll use at the
  289. // end.
  290. ssize_t i = 0;
  291. for (auto _ : state) {
  292. benchmark::DoNotOptimize(i);
  293. SetWrapperT s;
  294. for (auto k : keys) {
  295. bool inserted = s.BenchInsert(k);
  296. CARBON_DCHECK(inserted) << "Must be a successful insert!";
  297. }
  298. // Now insert a final random repeated key.
  299. bool inserted = s.BenchInsert(lookup_keys[i]);
  300. CARBON_DCHECK(!inserted) << "Must already be in the map!";
  301. // Rotate through the shuffled keys.
  302. i = (i + static_cast<ssize_t>(!inserted)) & (LookupKeysSize - 1);
  303. }
  304. // It can be easier in some cases to think of this as a key-throughput rate of
  305. // insertion rather than the latency of inserting N keys, so construct the
  306. // rate counter as well.
  307. state.counters["KeyRate"] = benchmark::Counter(
  308. keys.size(), benchmark::Counter::kIsIterationInvariantRate);
  309. // Report some extra statistics about the Carbon type.
  310. if constexpr (IsCarbonSet<SetT>) {
  311. // Re-build a set outside of the timing loop to look at the statistics
  312. // rather than the timing.
  313. SetT s;
  314. for (auto k : keys) {
  315. bool inserted = s.Insert(k).is_inserted();
  316. CARBON_DCHECK(inserted) << "Must be a successful insert!";
  317. }
  318. ReportTableMetrics(s, state);
  319. // Uncomment this call to print out statistics about the index-collisions
  320. // among these keys for debugging:
  321. //
  322. // RawHashtable::DumpHashStatistics(raw_keys);
  323. }
  324. }
  325. MAP_BENCHMARK_OP_SEQ(BM_SetInsertSeq);
  326. } // namespace
  327. } // namespace Carbon