2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 #include <folly/AtomicUnorderedMap.h>
17 #include <folly/test/DeterministicSchedule.h>
19 #include <semaphore.h>
20 #include <gflags/gflags.h>
21 #include <gtest/gtest.h>
22 #include <folly/Benchmark.h>
23 #include <unordered_map>
25 using namespace folly;
26 using namespace folly::test;
32 non_atomic() = default;
33 non_atomic(const non_atomic&) = delete;
34 constexpr /* implicit */ non_atomic(T desired): value(desired) {}
36 T operator+=(T arg) { value += arg; return load();}
38 T load(std::memory_order /* order */ = std::memory_order_seq_cst) const {
43 operator T() const {return load();}
46 std::memory_order /* order */ = std::memory_order_seq_cst) {
51 std::memory_order /* order */ = std::memory_order_seq_cst) {
57 bool compare_exchange_weak(
60 std::memory_order /* success */ = std::memory_order_seq_cst,
61 std::memory_order /* failure */ = std::memory_order_seq_cst) {
62 if (value == expected) {
71 bool compare_exchange_strong(
74 std::memory_order /* success */ = std::memory_order_seq_cst,
75 std::memory_order /* failure */ = std::memory_order_seq_cst) {
76 if (value == expected) {
85 bool is_lock_free() const {return true;}
88 template <typename Key,
91 template <typename> class Atom = std::atomic,
92 typename Allocator = std::allocator<char>>
94 AtomicUnorderedInsertMap<Key,
98 (boost::has_trivial_destructor<Key>::value &&
99 boost::has_trivial_destructor<Value>::value),
105 template <typename T>
106 struct AtomicUnorderedInsertMapTest : public ::testing::Test {};
109 // uint16_t doesn't make sense for most platforms, but we might as well
111 using IndexTypesToTest = ::testing::Types<uint16_t, uint32_t, uint64_t>;
112 TYPED_TEST_CASE(AtomicUnorderedInsertMapTest, IndexTypesToTest);
114 TYPED_TEST(AtomicUnorderedInsertMapTest, basic) {
119 folly::detail::MMapAlloc> m(100);
121 m.emplace("abc", "ABC");
122 EXPECT_TRUE(m.find("abc") != m.cend());
123 EXPECT_EQ(m.find("abc")->first, "abc");
124 EXPECT_EQ(m.find("abc")->second, "ABC");
125 EXPECT_TRUE(m.find("def") == m.cend());
126 auto iter = m.cbegin();
127 EXPECT_TRUE(iter != m.cend());
128 EXPECT_TRUE(iter == m.find("abc"));
130 EXPECT_TRUE(a == iter);
133 EXPECT_TRUE(iter == m.cend());
135 EXPECT_TRUE(a != iter);
137 EXPECT_TRUE(a == iter);
141 TEST(AtomicUnorderedInsertMap, load_factor) {
142 AtomicUnorderedInsertMap<int, bool> m(5000, 0.5f);
144 // we should be able to put in much more than 5000 things because of
145 // our load factor request
146 for (int i = 0; i < 10000; ++i) {
151 TEST(AtomicUnorderedInsertMap, capacity_exceeded) {
152 AtomicUnorderedInsertMap<int, bool> m(5000, 1.0f);
155 for (int i = 0; i < 6000; ++i) {
161 TYPED_TEST(AtomicUnorderedInsertMapTest, value_mutation) {
162 UIM<int, MutableAtom<int>, TypeParam> m(100);
164 for (int i = 0; i < 50; ++i) {
168 m.find(1)->second.data++;
171 TEST(UnorderedInsertMap, value_mutation) {
172 UIM<int, MutableData<int>, uint32_t, non_atomic> m(100);
174 for (int i = 0; i < 50; ++i) {
178 m.find(1)->second.data++;
179 EXPECT_EQ(m.find(1)->second.data, 2);
182 // This test is too expensive to run automatically. On my dev server it
183 // takes about 10 minutes for dbg build, 2 for opt.
184 TEST(AtomicUnorderedInsertMap, DISABLED_mega_map) {
185 size_t capacity = 2000000000;
186 AtomicUnorderedInsertMap64<size_t,size_t> big(capacity);
187 for (size_t i = 0; i < capacity * 2; i += 2) {
188 big.emplace(i, i * 10);
190 for (size_t i = 0; i < capacity * 3; i += capacity / 1000 + 1) {
191 auto iter = big.find(i);
192 if ((i & 1) == 0 && i < capacity * 2) {
193 EXPECT_EQ(iter->second, i * 10);
195 EXPECT_TRUE(iter == big.cend());
200 BENCHMARK(lookup_int_int_hit, iters) {
201 std::unique_ptr<AtomicUnorderedInsertMap<int,size_t>> ptr = {};
203 size_t capacity = 100000;
206 ptr.reset(new AtomicUnorderedInsertMap<int,size_t>(capacity));
207 for (size_t i = 0; i < capacity; ++i) {
208 auto k = 3 * ((5641 * i) % capacity);
209 ptr->emplace(k, k + 1);
210 EXPECT_EQ(ptr->find(k)->second, k + 1);
214 for (size_t i = 0; i < iters; ++i) {
215 size_t k = 3 * (((i * 7919) ^ (i * 4001)) % capacity);
216 auto iter = ptr->find(k);
217 if (iter == ptr->cend() ||
218 iter->second != k + 1) {
219 auto jter = ptr->find(k);
220 EXPECT_TRUE(iter == jter);
222 EXPECT_EQ(iter->second, k + 1);
231 size_t operator()(const std::pair<uint64_t,uint64_t>& pr) const {
232 return pr.first ^ pr.second;
236 void contendedRW(size_t itersPerThread,
239 size_t readsPerWrite) {
240 typedef std::pair<uint64_t,uint64_t> Key;
241 typedef AtomicUnorderedInsertMap<Key,MutableAtom<uint32_t>,PairHash> Map;
243 std::unique_ptr<Map> ptr = {};
244 std::atomic<bool> go;
245 std::vector<std::thread> threads;
248 ptr.reset(new Map(capacity));
249 while (threads.size() < numThreads) {
250 threads.emplace_back([&](){
252 std::this_thread::yield();
257 while (reads + writes < itersPerThread) {
258 auto r = Random::rand32();
259 Key key(reads + writes, r);
260 if (reads < writes * readsPerWrite ||
261 writes >= capacity / numThreads) {
264 auto iter = ptr->find(key);
266 iter == ptr->cend() ||
267 iter->second.data.load(std::memory_order_acquire) >= key.first);
271 auto pr = ptr->emplace(key, key.first);
273 pr.first->second.data++;
275 } catch (std::bad_alloc& x) {
276 LOG(INFO) << "bad alloc";
286 for (auto& thr : threads) {
295 // sudo nice -n -20 ~/fbcode/_bin/common/concurrency/experimental/atomic_unordered_map --benchmark --bm_min_iters=1000000
297 // without MAP_HUGETLB (default)
299 // ============================================================================
300 // common/concurrency/experimental/AtomicUnorderedMapTest.cpprelative time/iter
302 // ============================================================================
303 // lookup_int_int_hit 20.05ns 49.89M
304 // contendedRW(small_32thr_99pct) 70.36ns 14.21M
305 // contendedRW(large_32thr_99pct) 164.23ns 6.09M
306 // contendedRW(large_32thr_99_9pct) 158.81ns 6.30M
307 // ============================================================================
309 // with MAP_HUGETLB hacked in
310 // ============================================================================
311 // lookup_int_int_hit 19.67ns 50.84M
312 // contendedRW(small_32thr_99pct) 62.46ns 16.01M
313 // contendedRW(large_32thr_99pct) 119.41ns 8.37M
314 // contendedRW(large_32thr_99_9pct) 111.23ns 8.99M
315 // ============================================================================
316 BENCHMARK_NAMED_PARAM(contendedRW, small_32thr_99pct, 100000, 32, 99)
317 BENCHMARK_NAMED_PARAM(contendedRW, large_32thr_99pct, 100000000, 32, 99)
318 BENCHMARK_NAMED_PARAM(contendedRW, large_32thr_99_9pct, 100000000, 32, 999)
320 BENCHMARK_DRAW_LINE();
322 // sudo nice -n -20 ~/fbcode/_build/opt/site_integrity/quasar/experimental/atomic_unordered_map_test --benchmark --bm_min_iters=10000
323 // Single threaded benchmarks to test how much better we are than
324 // std::unordered_map and what is the cost of using atomic operations
325 // in the uncontended use case
326 // ============================================================================
327 // std_map 1.20ms 832.58
328 // atomic_fast_map 511.35us 1.96K
329 // fast_map 196.28us 5.09K
330 // ============================================================================
333 std::unordered_map<long, long> m;
335 for (int i=0; i<10000; ++i) {
339 for (int i=0; i<10000; ++i) {
341 folly::doNotOptimizeAway(&*a);
345 BENCHMARK(atomic_fast_map) {
346 UIM<long, long, uint32_t, std::atomic> m(10000);
347 for (int i=0; i<10000; ++i) {
351 for (int i=0; i<10000; ++i) {
353 folly::doNotOptimizeAway(&*a);
357 BENCHMARK(fast_map) {
358 UIM<long, long, uint32_t, non_atomic> m(10000);
359 for (int i=0; i<10000; ++i) {
363 for (int i=0; i<10000; ++i) {
365 folly::doNotOptimizeAway(&*a);
369 BENCHMARK(atomic_fast_map_64) {
370 UIM<long, long, uint64_t, std::atomic> m(10000);
371 for (int i=0; i<10000; ++i) {
375 for (int i=0; i<10000; ++i) {
377 folly::doNotOptimizeAway(&*a);
381 BENCHMARK(fast_map_64) {
382 UIM<long, long, uint64_t, non_atomic> m(10000);
383 for (int i=0; i<10000; ++i) {
387 for (int i=0; i<10000; ++i) {
389 folly::doNotOptimizeAway(&*a);
394 int main(int argc, char ** argv) {
395 testing::InitGoogleTest(&argc, argv);
396 google::ParseCommandLineFlags(&argc, &argv, true);
397 int rv = RUN_ALL_TESTS();
398 folly::runBenchmarksOnFlag();