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.
17 #include <folly/AtomicUnorderedMap.h>
19 #include <semaphore.h>
21 #include <unordered_map>
23 #include <folly/Benchmark.h>
24 #include <folly/portability/GFlags.h>
25 #include <folly/portability/GTest.h>
26 #include <folly/test/DeterministicSchedule.h>
28 using namespace folly;
29 using namespace folly::test;
35 non_atomic() = default;
36 non_atomic(const non_atomic&) = delete;
37 constexpr /* implicit */ non_atomic(T desired): value(desired) {}
39 T operator+=(T arg) { value += arg; return load();}
41 T load(std::memory_order /* order */ = std::memory_order_seq_cst) const {
46 operator T() const {return load();}
49 std::memory_order /* order */ = std::memory_order_seq_cst) {
54 std::memory_order /* order */ = std::memory_order_seq_cst) {
60 bool compare_exchange_weak(
63 std::memory_order /* success */ = std::memory_order_seq_cst,
64 std::memory_order /* failure */ = std::memory_order_seq_cst) {
65 if (value == expected) {
74 bool compare_exchange_strong(
77 std::memory_order /* success */ = std::memory_order_seq_cst,
78 std::memory_order /* failure */ = std::memory_order_seq_cst) {
79 if (value == expected) {
88 bool is_lock_free() const {return true;}
91 template <typename Key,
94 template <typename> class Atom = std::atomic,
95 typename Allocator = std::allocator<char>>
97 AtomicUnorderedInsertMap<Key,
101 (boost::has_trivial_destructor<Key>::value &&
102 boost::has_trivial_destructor<Value>::value),
108 template <typename T>
109 struct AtomicUnorderedInsertMapTest : public ::testing::Test {};
112 // uint16_t doesn't make sense for most platforms, but we might as well
114 using IndexTypesToTest = ::testing::Types<uint16_t, uint32_t, uint64_t>;
115 TYPED_TEST_CASE(AtomicUnorderedInsertMapTest, IndexTypesToTest);
117 TYPED_TEST(AtomicUnorderedInsertMapTest, basic) {
122 folly::detail::MMapAlloc> m(100);
124 m.emplace("abc", "ABC");
125 EXPECT_TRUE(m.find("abc") != m.cend());
126 EXPECT_EQ(m.find("abc")->first, "abc");
127 EXPECT_EQ(m.find("abc")->second, "ABC");
128 EXPECT_TRUE(m.find("def") == m.cend());
129 auto iter = m.cbegin();
130 EXPECT_TRUE(iter != m.cend());
131 EXPECT_TRUE(iter == m.find("abc"));
133 EXPECT_TRUE(a == iter);
136 EXPECT_TRUE(iter == m.cend());
138 EXPECT_TRUE(a != iter);
140 EXPECT_TRUE(a == iter);
144 TEST(AtomicUnorderedInsertMap, load_factor) {
145 AtomicUnorderedInsertMap<int, bool> m(5000, 0.5f);
147 // we should be able to put in much more than 5000 things because of
148 // our load factor request
149 for (int i = 0; i < 10000; ++i) {
154 TEST(AtomicUnorderedInsertMap, capacity_exceeded) {
155 AtomicUnorderedInsertMap<int, bool> m(5000, 1.0f);
158 for (int i = 0; i < 6000; ++i) {
164 TYPED_TEST(AtomicUnorderedInsertMapTest, value_mutation) {
165 UIM<int, MutableAtom<int>, TypeParam> m(100);
167 for (int i = 0; i < 50; ++i) {
171 m.find(1)->second.data++;
174 TEST(UnorderedInsertMap, value_mutation) {
175 UIM<int, MutableData<int>, uint32_t, non_atomic> m(100);
177 for (int i = 0; i < 50; ++i) {
181 m.find(1)->second.data++;
182 EXPECT_EQ(m.find(1)->second.data, 2);
185 // This test is too expensive to run automatically. On my dev server it
186 // takes about 10 minutes for dbg build, 2 for opt.
187 TEST(AtomicUnorderedInsertMap, DISABLED_mega_map) {
188 size_t capacity = 2000000000;
189 AtomicUnorderedInsertMap64<size_t,size_t> big(capacity);
190 for (size_t i = 0; i < capacity * 2; i += 2) {
191 big.emplace(i, i * 10);
193 for (size_t i = 0; i < capacity * 3; i += capacity / 1000 + 1) {
194 auto iter = big.find(i);
195 if ((i & 1) == 0 && i < capacity * 2) {
196 EXPECT_EQ(iter->second, i * 10);
198 EXPECT_TRUE(iter == big.cend());
203 BENCHMARK(lookup_int_int_hit, iters) {
204 std::unique_ptr<AtomicUnorderedInsertMap<int,size_t>> ptr = {};
206 size_t capacity = 100000;
209 ptr.reset(new AtomicUnorderedInsertMap<int,size_t>(capacity));
210 for (size_t i = 0; i < capacity; ++i) {
211 auto k = 3 * ((5641 * i) % capacity);
212 ptr->emplace(k, k + 1);
213 EXPECT_EQ(ptr->find(k)->second, k + 1);
217 for (size_t i = 0; i < iters; ++i) {
218 size_t k = 3 * (((i * 7919) ^ (i * 4001)) % capacity);
219 auto iter = ptr->find(k);
220 if (iter == ptr->cend() ||
221 iter->second != k + 1) {
222 auto jter = ptr->find(k);
223 EXPECT_TRUE(iter == jter);
225 EXPECT_EQ(iter->second, k + 1);
234 size_t operator()(const std::pair<uint64_t,uint64_t>& pr) const {
235 return pr.first ^ pr.second;
239 void contendedRW(size_t itersPerThread,
242 size_t readsPerWrite) {
243 typedef std::pair<uint64_t,uint64_t> Key;
244 typedef AtomicUnorderedInsertMap<Key,MutableAtom<uint32_t>,PairHash> Map;
246 std::unique_ptr<Map> ptr = {};
247 std::atomic<bool> go;
248 std::vector<std::thread> threads;
251 ptr.reset(new Map(capacity));
252 while (threads.size() < numThreads) {
253 threads.emplace_back([&](){
255 std::this_thread::yield();
260 while (reads + writes < itersPerThread) {
261 auto r = Random::rand32();
262 Key key(reads + writes, r);
263 if (reads < writes * readsPerWrite ||
264 writes >= capacity / numThreads) {
267 auto iter = ptr->find(key);
269 iter == ptr->cend() ||
270 iter->second.data.load(std::memory_order_acquire) >= key.first);
274 auto pr = ptr->emplace(key, key.first);
276 pr.first->second.data++;
278 } catch (std::bad_alloc&) {
279 LOG(INFO) << "bad alloc";
289 for (auto& thr : threads) {
298 // sudo nice -n -20 ~/fbcode/_bin/common/concurrency/experimental/atomic_unordered_map --benchmark --bm_min_iters=1000000
300 // without MAP_HUGETLB (default)
302 // ============================================================================
303 // common/concurrency/experimental/AtomicUnorderedMapTest.cpprelative time/iter
305 // ============================================================================
306 // lookup_int_int_hit 20.05ns 49.89M
307 // contendedRW(small_32thr_99pct) 70.36ns 14.21M
308 // contendedRW(large_32thr_99pct) 164.23ns 6.09M
309 // contendedRW(large_32thr_99_9pct) 158.81ns 6.30M
310 // ============================================================================
312 // with MAP_HUGETLB hacked in
313 // ============================================================================
314 // lookup_int_int_hit 19.67ns 50.84M
315 // contendedRW(small_32thr_99pct) 62.46ns 16.01M
316 // contendedRW(large_32thr_99pct) 119.41ns 8.37M
317 // contendedRW(large_32thr_99_9pct) 111.23ns 8.99M
318 // ============================================================================
319 BENCHMARK_NAMED_PARAM(contendedRW, small_32thr_99pct, 100000, 32, 99)
320 BENCHMARK_NAMED_PARAM(contendedRW, large_32thr_99pct, 100000000, 32, 99)
321 BENCHMARK_NAMED_PARAM(contendedRW, large_32thr_99_9pct, 100000000, 32, 999)
323 BENCHMARK_DRAW_LINE();
325 // sudo nice -n -20 ~/fbcode/_build/opt/site_integrity/quasar/experimental/atomic_unordered_map_test --benchmark --bm_min_iters=10000
326 // Single threaded benchmarks to test how much better we are than
327 // std::unordered_map and what is the cost of using atomic operations
328 // in the uncontended use case
329 // ============================================================================
330 // std_map 1.20ms 832.58
331 // atomic_fast_map 511.35us 1.96K
332 // fast_map 196.28us 5.09K
333 // ============================================================================
336 std::unordered_map<long, long> m;
338 for (int i=0; i<10000; ++i) {
342 for (int i=0; i<10000; ++i) {
344 folly::doNotOptimizeAway(&*a);
348 BENCHMARK(atomic_fast_map) {
349 UIM<long, long, uint32_t, std::atomic> m(10000);
350 for (int i=0; i<10000; ++i) {
354 for (int i=0; i<10000; ++i) {
356 folly::doNotOptimizeAway(&*a);
360 BENCHMARK(fast_map) {
361 UIM<long, long, uint32_t, non_atomic> m(10000);
362 for (int i=0; i<10000; ++i) {
366 for (int i=0; i<10000; ++i) {
368 folly::doNotOptimizeAway(&*a);
372 BENCHMARK(atomic_fast_map_64) {
373 UIM<long, long, uint64_t, std::atomic> m(10000);
374 for (int i=0; i<10000; ++i) {
378 for (int i=0; i<10000; ++i) {
380 folly::doNotOptimizeAway(&*a);
384 BENCHMARK(fast_map_64) {
385 UIM<long, long, uint64_t, non_atomic> m(10000);
386 for (int i=0; i<10000; ++i) {
390 for (int i=0; i<10000; ++i) {
392 folly::doNotOptimizeAway(&*a);
397 int main(int argc, char ** argv) {
398 testing::InitGoogleTest(&argc, argv);
399 gflags::ParseCommandLineFlags(&argc, &argv, true);
400 int rv = RUN_ALL_TESTS();
401 folly::runBenchmarksOnFlag();