templatize AtomicUnorderedInsertMap's internals to allow big maps
[folly.git] / folly / test / AtomicUnorderedMapTest.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <folly/AtomicUnorderedMap.h>
17 #include <folly/test/DeterministicSchedule.h>
18 #include <thread>
19 #include <semaphore.h>
20 #include <gflags/gflags.h>
21 #include <gtest/gtest.h>
22 #include <folly/Benchmark.h>
23 #include <unordered_map>
24
25 using namespace folly;
26 using namespace folly::test;
27
28 template<class T>
29 struct non_atomic {
30   T value;
31
32   non_atomic() = default;
33   non_atomic(const non_atomic&) = delete;
34   constexpr /* implicit */ non_atomic(T desired): value(desired) {}
35
36   T operator+=(T arg) { value += arg; return load();}
37
38   T load(std::memory_order order= std::memory_order_seq_cst) const {
39     return value;
40   }
41
42   /* implicit */
43   operator T() const {return load();}
44
45   void store(T desired, std::memory_order order = std::memory_order_seq_cst) {
46     value = desired;
47   }
48
49   T exchange(T desired, std::memory_order order = std::memory_order_seq_cst) {
50     T old = load();
51     store(desired);
52     return old;
53   }
54
55   bool compare_exchange_weak(
56       T& expected, T desired,
57       std::memory_order success = std::memory_order_seq_cst,
58       std::memory_order failure = std::memory_order_seq_cst) {
59     if (value == expected) {
60       value = desired;
61       return true;
62     }
63
64     expected = value;
65     return false;
66   }
67
68   bool compare_exchange_strong(
69       T& expected, T desired,
70       std::memory_order success = std::memory_order_seq_cst,
71       std::memory_order failure = std::memory_order_seq_cst) {
72     if (value == expected) {
73       value = desired;
74       return true;
75     }
76
77     expected = value;
78     return false;
79   }
80
81   bool is_lock_free() const {return true;}
82 };
83
84 template <typename Key,
85           typename Value,
86           typename IndexType,
87           template <typename> class Atom = std::atomic,
88           typename Allocator = std::allocator<char>>
89 using UIM =
90     AtomicUnorderedInsertMap<Key,
91                              Value,
92                              std::hash<Key>,
93                              std::equal_to<Key>,
94                              (boost::has_trivial_destructor<Key>::value &&
95                               boost::has_trivial_destructor<Value>::value),
96                              Atom,
97                              Allocator,
98                              IndexType>;
99
100 namespace {
101 template <typename T>
102 struct AtomicUnorderedInsertMapTest : public ::testing::Test {};
103 }
104
105 // uint16_t doesn't make sense for most platforms, but we might as well
106 // test it
107 using IndexTypesToTest = ::testing::Types<uint16_t, uint32_t, uint64_t>;
108 TYPED_TEST_CASE(AtomicUnorderedInsertMapTest, IndexTypesToTest);
109
110 TYPED_TEST(AtomicUnorderedInsertMapTest, basic) {
111   UIM<std::string,
112       std::string,
113       TypeParam,
114       std::atomic,
115       folly::detail::MMapAlloc> m(100);
116
117   m.emplace("abc", "ABC");
118   EXPECT_TRUE(m.find("abc") != m.cend());
119   EXPECT_EQ(m.find("abc")->first, "abc");
120   EXPECT_EQ(m.find("abc")->second, "ABC");
121   EXPECT_TRUE(m.find("def") == m.cend());
122   auto iter = m.cbegin();
123   EXPECT_TRUE(iter != m.cend());
124   EXPECT_TRUE(iter == m.find("abc"));
125   auto a = iter;
126   EXPECT_TRUE(a == iter);
127   auto b = iter;
128   ++iter;
129   EXPECT_TRUE(iter == m.cend());
130   EXPECT_TRUE(a == b);
131   EXPECT_TRUE(a != iter);
132   a++;
133   EXPECT_TRUE(a == iter);
134   EXPECT_TRUE(a != b);
135 }
136
137 TYPED_TEST(AtomicUnorderedInsertMapTest, value_mutation) {
138   UIM<int, MutableAtom<int>, TypeParam> m(100);
139
140   for (int i = 0; i < 50; ++i) {
141     m.emplace(i, i);
142   }
143
144   m.find(1)->second.data++;
145 }
146
147 TEST(UnorderedInsertMap, value_mutation) {
148   UIM<int, MutableData<int>, uint32_t, non_atomic> m(100);
149
150   for (int i = 0; i < 50; ++i) {
151     m.emplace(i, i);
152   }
153
154   m.find(1)->second.data++;
155   EXPECT_EQ(m.find(1)->second.data, 2);
156 }
157
158 // This test is too expensive to run automatically.  On my dev server it
159 // takes about 10 minutes for dbg build, 2 for opt.
160 TEST(AtomicUnorderedInsertMap, DISABLED_mega_map) {
161   size_t capacity = 2000000000;
162   AtomicUnorderedInsertMap64<size_t,size_t> big(capacity);
163   for (size_t i = 0; i < capacity * 2; i += 2) {
164     big.emplace(i, i * 10);
165   }
166   for (size_t i = 0; i < capacity * 3; i += capacity / 1000 + 1) {
167     auto iter = big.find(i);
168     if ((i & 1) == 0 && i < capacity * 2) {
169       EXPECT_EQ(iter->second, i * 10);
170     } else {
171       EXPECT_TRUE(iter == big.cend());
172     }
173   }
174 }
175
176 BENCHMARK(lookup_int_int_hit, iters) {
177   std::unique_ptr<AtomicUnorderedInsertMap<int,size_t>> ptr = {};
178
179   size_t capacity = 100000;
180
181   BENCHMARK_SUSPEND {
182     ptr.reset(new AtomicUnorderedInsertMap<int,size_t>(capacity));
183     for (size_t i = 0; i < capacity; ++i) {
184       auto k = 3 * ((5641 * i) % capacity);
185       ptr->emplace(k, k + 1);
186       EXPECT_EQ(ptr->find(k)->second, k + 1);
187     }
188   }
189
190   for (size_t i = 0; i < iters; ++i) {
191     size_t k = 3 * (((i * 7919) ^ (i * 4001)) % capacity);
192     auto iter = ptr->find(k);
193     if (iter == ptr->cend() ||
194         iter->second != k + 1) {
195       auto jter = ptr->find(k);
196       EXPECT_TRUE(iter == jter);
197     }
198     EXPECT_EQ(iter->second, k + 1);
199   }
200
201   BENCHMARK_SUSPEND {
202     ptr.reset(nullptr);
203   }
204 }
205
206 struct PairHash {
207   size_t operator()(const std::pair<uint64_t,uint64_t>& pr) const {
208     return pr.first ^ pr.second;
209   }
210 };
211
212 void contendedRW(size_t itersPerThread,
213                  size_t capacity,
214                  size_t numThreads,
215                  size_t readsPerWrite) {
216   typedef std::pair<uint64_t,uint64_t> Key;
217   typedef AtomicUnorderedInsertMap<Key,MutableAtom<uint32_t>,PairHash> Map;
218
219   std::unique_ptr<Map> ptr = {};
220   std::atomic<bool> go;
221   std::vector<std::thread> threads;
222
223   BENCHMARK_SUSPEND {
224     ptr.reset(new Map(capacity));
225     while (threads.size() < numThreads) {
226       threads.emplace_back([&](){
227         while (!go) {
228           std::this_thread::yield();
229         }
230
231         size_t reads = 0;
232         size_t writes = 0;
233         while (reads + writes < itersPerThread) {
234           auto r = Random::rand32();
235           Key key(reads + writes, r);
236           if (reads < writes * readsPerWrite ||
237               writes >= capacity / numThreads) {
238             // read needed
239             ++reads;
240             auto iter = ptr->find(key);
241             EXPECT_TRUE(
242                 iter == ptr->cend() ||
243                 iter->second.data.load(std::memory_order_acquire) >= key.first);
244           } else {
245             ++writes;
246             try {
247               auto pr = ptr->emplace(key, key.first);
248               if (!pr.second) {
249                 pr.first->second.data++;
250               }
251             } catch (std::bad_alloc& x) {
252               LOG(INFO) << "bad alloc";
253             }
254           }
255         }
256       });
257     }
258   }
259
260   go = true;
261
262   for (auto& thr : threads) {
263     thr.join();
264   }
265
266   BENCHMARK_SUSPEND {
267     ptr.reset(nullptr);
268   }
269 }
270
271 // sudo nice -n -20 ~/fbcode/_bin/common/concurrency/experimental/atomic_unordered_map --benchmark --bm_min_iters=1000000
272 //
273 // without MAP_HUGETLB (default)
274 //
275 // ============================================================================
276 // common/concurrency/experimental/AtomicUnorderedMapTest.cpprelative  time/iter
277 //   iters/s
278 // ============================================================================
279 // lookup_int_int_hit                                          20.05ns   49.89M
280 // contendedRW(small_32thr_99pct)                              70.36ns   14.21M
281 // contendedRW(large_32thr_99pct)                             164.23ns    6.09M
282 // contendedRW(large_32thr_99_9pct)                           158.81ns    6.30M
283 // ============================================================================
284 //
285 // with MAP_HUGETLB hacked in
286 // ============================================================================
287 // lookup_int_int_hit                                          19.67ns   50.84M
288 // contendedRW(small_32thr_99pct)                              62.46ns   16.01M
289 // contendedRW(large_32thr_99pct)                             119.41ns    8.37M
290 // contendedRW(large_32thr_99_9pct)                           111.23ns    8.99M
291 // ============================================================================
292 BENCHMARK_NAMED_PARAM(contendedRW, small_32thr_99pct, 100000, 32, 99)
293 BENCHMARK_NAMED_PARAM(contendedRW, large_32thr_99pct, 100000000, 32, 99)
294 BENCHMARK_NAMED_PARAM(contendedRW, large_32thr_99_9pct, 100000000, 32, 999)
295
296 BENCHMARK_DRAW_LINE();
297
298 // sudo nice -n -20 ~/fbcode/_build/opt/site_integrity/quasar/experimental/atomic_unordered_map_test --benchmark --bm_min_iters=10000
299 // Single threaded benchmarks to test how much better we are than
300 // std::unordered_map and what is the cost of using atomic operations
301 // in the uncontended use case
302 // ============================================================================
303 // std_map                                                      1.20ms   832.58
304 // atomic_fast_map                                            511.35us    1.96K
305 // fast_map                                                   196.28us    5.09K
306 // ============================================================================
307
308 BENCHMARK(std_map) {
309   std::unordered_map<long, long> m;
310   m.reserve(10000);
311   for (int i=0; i<10000; ++i) {
312     m.emplace(i,i);
313   }
314
315   for (int i=0; i<10000; ++i) {
316     auto a = m.find(i);
317     folly::doNotOptimizeAway(&*a);
318   }
319 }
320
321 BENCHMARK(atomic_fast_map) {
322   UIM<long, long, uint32_t, std::atomic> m(10000);
323   for (int i=0; i<10000; ++i) {
324     m.emplace(i,i);
325   }
326
327   for (int i=0; i<10000; ++i) {
328     auto a = m.find(i);
329     folly::doNotOptimizeAway(&*a);
330   }
331 }
332
333 BENCHMARK(fast_map) {
334   UIM<long, long, uint32_t, non_atomic> m(10000);
335   for (int i=0; i<10000; ++i) {
336     m.emplace(i,i);
337   }
338
339   for (int i=0; i<10000; ++i) {
340     auto a = m.find(i);
341     folly::doNotOptimizeAway(&*a);
342   }
343 }
344
345 BENCHMARK(atomic_fast_map_64) {
346   UIM<long, long, uint64_t, std::atomic> m(10000);
347   for (int i=0; i<10000; ++i) {
348     m.emplace(i,i);
349   }
350
351   for (int i=0; i<10000; ++i) {
352     auto a = m.find(i);
353     folly::doNotOptimizeAway(&*a);
354   }
355 }
356
357 BENCHMARK(fast_map_64) {
358   UIM<long, long, uint64_t, non_atomic> m(10000);
359   for (int i=0; i<10000; ++i) {
360     m.emplace(i,i);
361   }
362
363   for (int i=0; i<10000; ++i) {
364     auto a = m.find(i);
365     folly::doNotOptimizeAway(&*a);
366   }
367 }
368
369
370 int main(int argc, char ** argv) {
371   testing::InitGoogleTest(&argc, argv);
372   google::ParseCommandLineFlags(&argc, &argv, true);
373   int rv = RUN_ALL_TESTS();
374   folly::runBenchmarksOnFlag();
375   return rv;
376 }