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/AtomicHashMap.h>
19 #include <glog/logging.h>
24 #include <folly/Assume.h>
25 #include <folly/Benchmark.h>
26 #include <folly/Conv.h>
27 #include <folly/portability/GTest.h>
28 #include <folly/portability/SysTime.h>
32 using folly::AtomicHashMap;
33 using folly::AtomicHashArray;
34 using folly::StringPiece;
37 DEFINE_double(targetLoadFactor, 0.75, "Target memory utilization fraction.");
38 DEFINE_double(maxLoadFactor, 0.80, "Max before growth.");
39 DEFINE_int32(numThreads, 8, "Threads to use for concurrency tests.");
40 DEFINE_int64(numBMElements, 12 * 1000 * 1000, "Size of maps for benchmarks.");
42 const double LF = FLAGS_maxLoadFactor / FLAGS_targetLoadFactor;
43 const int maxBMElements = int(FLAGS_numBMElements * LF); // hit our target LF.
45 static int64_t nowInUsec() {
48 return int64_t(tv.tv_sec) * 1000 * 1000 + tv.tv_usec;
51 TEST(Ahm, BasicStrings) {
52 typedef AtomicHashMap<int64_t,string> AHM;
54 EXPECT_TRUE(myMap.begin() == myMap.end());
56 for (int i = 0; i < 100; ++i) {
57 myMap.insert(make_pair(i, folly::to<string>(i)));
59 for (int i = 0; i < 100; ++i) {
60 EXPECT_EQ(myMap.find(i)->second, folly::to<string>(i));
63 myMap.insert(std::make_pair(999, "A"));
64 myMap.insert(std::make_pair(999, "B"));
65 EXPECT_EQ(myMap.find(999)->second, "A"); // shouldn't have overwritten
66 myMap.find(999)->second = "B";
67 myMap.find(999)->second = "C";
68 EXPECT_EQ(myMap.find(999)->second, "C");
69 EXPECT_EQ(myMap.find(999)->first, 999);
73 TEST(Ahm, BasicNoncopyable) {
74 typedef AtomicHashMap<int64_t,std::unique_ptr<int>> AHM;
76 EXPECT_TRUE(myMap.begin() == myMap.end());
78 for (int i = 0; i < 50; ++i) {
79 myMap.insert(make_pair(i, std::unique_ptr<int>(new int(i))));
81 for (int i = 50; i < 100; ++i) {
82 myMap.insert(i, std::unique_ptr<int>(new int (i)));
84 for (int i = 100; i < 150; ++i) {
85 myMap.emplace(i, new int (i));
87 for (int i = 150; i < 200; ++i) {
88 myMap.emplace(i, new int (i), std::default_delete<int>());
90 for (int i = 0; i < 200; ++i) {
91 EXPECT_EQ(*(myMap.find(i)->second), i);
93 for (int i = 0; i < 200; i+=4) {
96 for (int i = 0; i < 200; i+=4) {
97 EXPECT_EQ(myMap.find(i), myMap.end());
101 typedef int32_t KeyT;
102 typedef int32_t ValueT;
104 typedef AtomicHashMap<KeyT,ValueT> AHMapT;
105 typedef AHMapT::value_type RecordT;
106 typedef AtomicHashArray<KeyT,ValueT> AHArrayT;
107 AHArrayT::Config config;
108 typedef folly::QuadraticProbingAtomicHashMap<KeyT,ValueT> QPAHMapT;
109 QPAHMapT::Config qpConfig;
110 static AHArrayT::SmartPtr globalAHA(nullptr);
111 static std::unique_ptr<AHMapT> globalAHM;
112 static std::unique_ptr<QPAHMapT> globalQPAHM;
114 // Generate a deterministic value based on an input key
115 static int genVal(int key) {
119 static bool legalKey(const char* a);
122 bool operator()(const char* a, const char* b) {
123 return legalKey(a) && (strcmp(a, b) == 0);
125 bool operator()(const char* a, const char& b) {
126 return legalKey(a) && (a[0] != '\0') && (a[0] == b);
128 bool operator()(const char* a, const StringPiece b) {
129 return legalKey(a) &&
130 (strlen(a) == b.size()) && (strcmp(a, b.begin()) == 0);
135 size_t operator()(const char* a) {
137 while (a[0] != 0) result += static_cast<size_t>(*(a++));
140 size_t operator()(const char& a) {
141 return static_cast<size_t>(a);
143 size_t operator()(const StringPiece a) {
145 for (const auto& ch : a) result += static_cast<size_t>(ch);
150 typedef AtomicHashMap<const char*, int64_t, HashTraits, EqTraits> AHMCstrInt;
151 AHMCstrInt::Config cstrIntCfg;
153 static bool legalKey(const char* a) {
154 return a != cstrIntCfg.emptyKey &&
155 a != cstrIntCfg.lockedKey &&
156 a != cstrIntCfg.erasedKey;
159 TEST(Ahm, BasicLookup) {
160 AHMCstrInt myMap(1024, cstrIntCfg);
161 EXPECT_TRUE(myMap.begin() == myMap.end());
162 myMap.insert(std::make_pair("f", 42));
163 EXPECT_EQ(42, myMap.find("f")->second);
165 // Look up a single char, successfully.
166 auto it = myMap.find<char>('f');
167 EXPECT_EQ(42, it->second);
170 // Look up a single char, unsuccessfully.
171 auto it = myMap.find<char>('g');
172 EXPECT_TRUE(it == myMap.end());
175 // Look up a string piece, successfully.
176 const StringPiece piece("f");
177 auto it = myMap.find(piece);
178 EXPECT_EQ(42, it->second);
183 VLOG(1) << "Overhead: " << sizeof(AHArrayT) << " (array) " <<
184 sizeof(AHMapT) + sizeof(AHArrayT) << " (map/set) Bytes.";
185 uint64_t numEntries = 10000;
186 float sizeFactor = 0.46f;
188 std::unique_ptr<AHMapT> m(new AHMapT(int(numEntries * sizeFactor), config));
190 // load map - make sure we succeed and the index is accurate
192 for (uint64_t i = 0; i < numEntries; i++) {
193 auto ret = m->insert(RecordT(i, genVal(i)));
194 success &= ret.second;
195 success &= (m->findAt(ret.first.getIndex())->second == genVal(i));
197 // Overwrite vals to make sure there are no dups
198 // Every insert should fail because the keys are already in the map.
200 for (uint64_t i = 0; i < numEntries; i++) {
201 auto ret = m->insert(RecordT(i, genVal(i * 2)));
202 success &= (ret.second == false); // fail on collision
203 success &= (ret.first->second == genVal(i)); // return the previous value
204 success &= (m->findAt(ret.first.getIndex())->second == genVal(i));
206 EXPECT_TRUE(success);
209 EXPECT_GT(m->numSubMaps(), 1); // make sure we grew
211 EXPECT_EQ(m->size(), numEntries);
212 for (size_t i = 0; i < numEntries; i++) {
213 success &= (m->find(i)->second == genVal(i));
215 EXPECT_TRUE(success);
219 AHMapT::const_iterator retIt;
220 for (int32_t i = 0; i < int32_t(numEntries); i++) {
222 retIt = m->findAt(retIt.getIndex());
223 success &= (retIt->second == genVal(i));
224 // We use a uint32_t index so that this comparison is between two
225 // variables of the same type.
226 success &= (retIt->first == i);
228 EXPECT_TRUE(success);
230 // Try modifying value
231 m->find(8)->second = 5309;
232 EXPECT_EQ(m->find(8)->second, 5309);
237 for (uint64_t i = 0; i < numEntries / 2; i++) {
238 success &= m->insert(RecordT(i, genVal(i))).second;
240 EXPECT_TRUE(success);
241 EXPECT_EQ(m->size(), numEntries / 2);
244 TEST(Ahm, iterator) {
245 int numEntries = 10000;
246 float sizeFactor = .46f;
247 std::unique_ptr<AHMapT> m(new AHMapT(int(numEntries * sizeFactor), config));
249 // load map - make sure we succeed and the index is accurate
250 for (int i = 0; i < numEntries; i++) {
251 m->insert(RecordT(i, genVal(i)));
257 success &= (it->second == genVal(it->first));
260 EXPECT_TRUE(success);
261 EXPECT_EQ(count, numEntries);
266 // Note: Unfortunately can't currently put a std::atomic<int64_t> in
267 // the value in ahm since it doesn't support types that are both non-copy
268 // and non-move constructible yet.
269 AtomicHashMap<int64_t,int64_t> ahm;
272 explicit Counters(size_t numCounters) : ahm(numCounters) {}
274 void increment(int64_t obj_id) {
275 auto ret = ahm.insert(std::make_pair(obj_id, 1));
277 // obj_id already exists, increment count
278 __sync_fetch_and_add(&ret.first->second, 1);
282 int64_t getValue(int64_t obj_id) {
283 auto ret = ahm.find(obj_id);
284 return ret != ahm.end() ? ret->second : 0;
287 // export the counters without blocking increments
290 ret.reserve(ahm.size() * 32);
291 for (const auto& e : ahm) {
292 ret += folly::to<string>(
293 " [", e.first, ":", e.second, "]\n");
300 // If you get an error "terminate called without an active exception", there
301 // might be too many threads getting created - decrease numKeys and/or mult.
303 const int numKeys = 10;
306 vector<int64_t> keys;
307 FOR_EACH_RANGE(i, 1, numKeys) {
310 vector<std::thread> threads;
311 for (auto key : keys) {
312 FOR_EACH_RANGE(i, 0, key * mult) {
313 threads.push_back(std::thread([&, key] { c.increment(key); }));
316 for (auto& t : threads) {
319 string str = c.toString();
320 for (auto key : keys) {
321 int val = key * mult;
322 EXPECT_EQ(val, c.getValue(key));
323 EXPECT_NE(string::npos, str.find(folly::to<string>("[",key,":",val,"]")));
330 explicit Integer(KeyT v = 0) : v_(v) {}
332 Integer& operator=(const Integer& a) {
333 static bool throwException_ = false;
334 throwException_ = !throwException_;
335 if (throwException_) {
342 bool operator==(const Integer& a) const { return v_ == a.v_; }
348 TEST(Ahm, map_exception_safety) {
349 typedef AtomicHashMap<KeyT,Integer> MyMapT;
351 int numEntries = 10000;
352 float sizeFactor = 0.46f;
353 std::unique_ptr<MyMapT> m(new MyMapT(int(numEntries * sizeFactor)));
357 for (int i = 0; i < numEntries; i++) {
359 m->insert(i, Integer(genVal(i)));
360 success &= (m->find(i)->second == Integer(genVal(i)));
363 success &= !m->count(i);
366 EXPECT_EQ(count, m->size());
367 EXPECT_TRUE(success);
370 TEST(Ahm, basicErase) {
371 size_t numEntries = 3000;
373 std::unique_ptr<AHMapT> s(new AHMapT(numEntries, config));
374 // Iterate filling up the map and deleting all keys a few times
375 // to test more than one subMap.
376 for (int iterations = 0; iterations < 4; ++iterations) {
377 // Testing insertion of keys
379 for (size_t i = 0; i < numEntries; ++i) {
380 success &= !(s->count(i));
381 auto ret = s->insert(RecordT(i, i));
382 success &= s->count(i);
383 success &= ret.second;
385 EXPECT_TRUE(success);
386 EXPECT_EQ(s->size(), numEntries);
388 // Delete every key in the map and verify that the key is gone and the the
391 for (size_t i = 0; i < numEntries; ++i) {
392 success &= s->erase(i);
393 success &= (s->size() == numEntries - 1 - i);
394 success &= !(s->count(i));
395 success &= !(s->erase(i));
397 EXPECT_TRUE(success);
399 VLOG(1) << "Final number of subMaps = " << s->numSubMaps();
404 inline KeyT randomizeKey(int key) {
405 // We deterministically randomize the key to more accurately simulate
406 // real-world usage, and to avoid pathalogical performance patterns (e.g.
407 // those related to __gnu_cxx::hash<int64_t>()(1) == 1).
409 // Use a hash function we don't normally use for ints to avoid interactions.
410 return folly::hash::jenkins_rev_mix32(key);
413 int numOpsPerThread = 0;
415 void* insertThread(void* jj) {
416 int64_t j = (int64_t) jj;
417 for (int i = 0; i < numOpsPerThread; ++i) {
418 KeyT key = randomizeKey(i + j * numOpsPerThread);
419 globalAHM->insert(key, genVal(key));
424 void* qpInsertThread(void* jj) {
425 int64_t j = (int64_t) jj;
426 for (int i = 0; i < numOpsPerThread; ++i) {
427 KeyT key = randomizeKey(i + j * numOpsPerThread);
428 globalQPAHM->insert(key, genVal(key));
433 void* insertThreadArr(void* jj) {
434 int64_t j = (int64_t) jj;
435 for (int i = 0; i < numOpsPerThread; ++i) {
436 KeyT key = randomizeKey(i + j * numOpsPerThread);
437 globalAHA->insert(std::make_pair(key, genVal(key)));
442 std::atomic<bool> runThreadsCreatedAllThreads;
443 void runThreads(void *(*mainFunc)(void*), int numThreads, void **statuses) {
444 folly::BenchmarkSuspender susp;
445 runThreadsCreatedAllThreads.store(false);
446 vector<std::thread> threads;
447 for (int64_t j = 0; j < numThreads; j++) {
448 threads.emplace_back([statuses, mainFunc, j]() {
449 auto ret = mainFunc((void*)j);
450 if (statuses != nullptr) {
457 runThreadsCreatedAllThreads.store(true);
458 for (size_t i = 0; i < threads.size(); ++i) {
463 void runThreads(void *(*mainFunc)(void*)) {
464 runThreads(mainFunc, FLAGS_numThreads, nullptr);
469 TEST(Ahm, collision_test) {
470 const int numInserts = 1000000 / 4;
472 // Doing the same number on each thread so we collide.
473 numOpsPerThread = numInserts;
475 float sizeFactor = 0.46f;
476 int entrySize = sizeof(KeyT) + sizeof(ValueT);
477 VLOG(1) << "Testing " << numInserts << " unique " << entrySize <<
478 " Byte entries replicated in " << FLAGS_numThreads <<
479 " threads with " << FLAGS_maxLoadFactor * 100.0 << "% max load factor.";
481 globalAHM.reset(new AHMapT(int(numInserts * sizeFactor), config));
483 size_t sizeInit = globalAHM->capacity();
484 VLOG(1) << " Initial capacity: " << sizeInit;
486 double start = nowInUsec();
487 runThreads([](void*) -> void* { // collisionInsertThread
488 for (int i = 0; i < numOpsPerThread; ++i) {
489 KeyT key = randomizeKey(i);
490 globalAHM->insert(key, genVal(key));
494 double elapsed = nowInUsec() - start;
496 size_t finalCap = globalAHM->capacity();
497 size_t sizeAHM = globalAHM->size();
498 VLOG(1) << elapsed/sizeAHM << " usec per " << FLAGS_numThreads <<
499 " duplicate inserts (atomic).";
500 VLOG(1) << " Final capacity: " << finalCap << " in " <<
501 globalAHM->numSubMaps() << " sub maps (" <<
502 sizeAHM * 100 / finalCap << "% load factor, " <<
503 (finalCap - sizeInit) * 100 / sizeInit << "% growth).";
506 EXPECT_EQ(sizeAHM, numInserts);
508 for (int i = 0; i < numInserts; ++i) {
509 KeyT key = randomizeKey(i);
510 success &= (globalAHM->find(key)->second == genVal(key));
512 EXPECT_TRUE(success);
514 // check colliding finds
516 runThreads([](void*) -> void* { // collisionFindThread
518 for (int i = 0; i < numOpsPerThread; ++i) {
519 globalAHM->find(key);
524 elapsed = nowInUsec() - start;
526 VLOG(1) << elapsed/sizeAHM << " usec per " << FLAGS_numThreads <<
527 " duplicate finds (atomic).";
532 const int kInsertPerThread = 100000;
533 int raceFinalSizeEstimate;
535 void* raceIterateThread(void*) {
538 AHMapT::iterator it = globalAHM->begin();
539 AHMapT::iterator end = globalAHM->end();
540 for (; it != end; ++it) {
542 if (count > raceFinalSizeEstimate) {
543 EXPECT_FALSE("Infinite loop in iterator.");
550 void* raceInsertRandomThread(void*) {
551 for (int i = 0; i < kInsertPerThread; ++i) {
553 globalAHM->insert(key, genVal(key));
560 // Test for race conditions when inserting and iterating at the same time and
561 // creating multiple submaps.
562 TEST(Ahm, race_insert_iterate_thread_test) {
563 const int kInsertThreads = 20;
564 const int kIterateThreads = 20;
565 raceFinalSizeEstimate = kInsertThreads * kInsertPerThread;
567 VLOG(1) << "Testing iteration and insertion with " << kInsertThreads
568 << " threads inserting and " << kIterateThreads << " threads iterating.";
570 globalAHM.reset(new AHMapT(raceFinalSizeEstimate / 9, config));
572 vector<pthread_t> threadIds;
573 for (int j = 0; j < kInsertThreads + kIterateThreads; j++) {
575 void *(*thread)(void*) =
576 (j < kInsertThreads ? raceInsertRandomThread : raceIterateThread);
577 if (pthread_create(&tid, nullptr, thread, nullptr) != 0) {
578 LOG(ERROR) << "Could not start thread";
580 threadIds.push_back(tid);
583 for (size_t i = 0; i < threadIds.size(); ++i) {
584 pthread_join(threadIds[i], nullptr);
586 VLOG(1) << "Ended up with " << globalAHM->numSubMaps() << " submaps";
587 VLOG(1) << "Final size of map " << globalAHM->size();
592 const int kTestEraseInsertions = 200000;
593 std::atomic<int32_t> insertedLevel;
595 void* testEraseInsertThread(void*) {
596 for (int i = 0; i < kTestEraseInsertions; ++i) {
597 KeyT key = randomizeKey(i);
598 globalAHM->insert(key, genVal(key));
599 insertedLevel.store(i, std::memory_order_release);
601 insertedLevel.store(kTestEraseInsertions, std::memory_order_release);
605 void* testEraseEraseThread(void*) {
606 for (int i = 0; i < kTestEraseInsertions; ++i) {
608 * Make sure that we don't get ahead of the insert thread, because
609 * part of the condition for this unit test succeeding is that the
612 * Note, there is a subtle case here when a new submap is
613 * allocated: the erasing thread might get 0 from count(key)
614 * because it hasn't seen numSubMaps_ update yet. To avoid this
615 * race causing problems for the test (it's ok for real usage), we
616 * lag behind the inserter by more than just element.
621 currentLevel = insertedLevel.load(std::memory_order_acquire);
622 if (currentLevel == kTestEraseInsertions) currentLevel += lag + 1;
623 } while (currentLevel - lag < i);
625 KeyT key = randomizeKey(i);
626 while (globalAHM->count(key)) {
627 if (globalAHM->erase(key)) {
637 // Here we have a single thread inserting some values, and several threads
638 // racing to delete the values in the order they were inserted.
639 TEST(Ahm, thread_erase_insert_race) {
640 const int kInsertThreads = 1;
641 const int kEraseThreads = 10;
643 VLOG(1) << "Testing insertion and erase with " << kInsertThreads
644 << " thread inserting and " << kEraseThreads << " threads erasing.";
646 globalAHM.reset(new AHMapT(kTestEraseInsertions / 4, config));
648 vector<pthread_t> threadIds;
649 for (int64_t j = 0; j < kInsertThreads + kEraseThreads; j++) {
651 void *(*thread)(void*) =
652 (j < kInsertThreads ? testEraseInsertThread : testEraseEraseThread);
653 if (pthread_create(&tid, nullptr, thread, (void*) j) != 0) {
654 LOG(ERROR) << "Could not start thread";
656 threadIds.push_back(tid);
659 for (size_t i = 0; i < threadIds.size(); i++) {
660 pthread_join(threadIds[i], nullptr);
663 EXPECT_TRUE(globalAHM->empty());
664 EXPECT_EQ(globalAHM->size(), 0);
666 VLOG(1) << "Ended up with " << globalAHM->numSubMaps() << " submaps";
669 // Repro for T#483734: Duplicate AHM inserts due to incorrect AHA return value.
670 typedef AtomicHashArray<int32_t, int32_t> AHA;
671 AHA::Config configRace;
672 auto atomicHashArrayInsertRaceArray = AHA::create(2, configRace);
673 void* atomicHashArrayInsertRaceThread(void* /* j */) {
674 AHA* arr = atomicHashArrayInsertRaceArray.get();
675 uintptr_t numInserted = 0;
676 while (!runThreadsCreatedAllThreads.load());
677 for (int i = 0; i < 2; i++) {
678 if (arr->insert(RecordT(randomizeKey(i), 0)).first != arr->end()) {
682 return (void*)numInserted;
684 TEST(Ahm, atomic_hash_array_insert_race) {
685 AHA* arr = atomicHashArrayInsertRaceArray.get();
686 int numIterations = 5000;
687 constexpr int numThreads = 4;
688 void* statuses[numThreads];
689 for (int i = 0; i < numIterations; i++) {
691 runThreads(atomicHashArrayInsertRaceThread, numThreads, statuses);
692 EXPECT_GE(arr->size(), 1);
693 for (int j = 0; j < numThreads; j++) {
694 EXPECT_EQ(arr->size(), uintptr_t(statuses[j]));
699 // Repro for T#5841499. Race between erase() and find() on the same key.
700 TEST(Ahm, erase_find_race) {
701 const uint64_t limit = 10000;
702 AtomicHashMap<uint64_t, uint64_t> map(limit + 10);
703 std::atomic<uint64_t> key {1};
705 // Invariant: all values are equal to their keys.
706 // At any moment there is one or two consecutive keys in the map.
708 std::thread write_thread([&]() {
714 map.insert(k + 1, k + 1);
719 std::thread read_thread([&]() {
721 uint64_t k = key.load();
726 auto it = map.find(k);
727 if (it != map.end()) {
728 ASSERT_EQ(k, it->second);
737 // Erase right after insert race bug repro (t9130653)
738 TEST(Ahm, erase_after_insert_race) {
739 const uint64_t limit = 10000;
740 const size_t num_threads = 100;
741 const size_t num_iters = 500;
742 AtomicHashMap<uint64_t, uint64_t> map(limit + 10);
744 std::atomic<bool> go{false};
745 std::vector<std::thread> ts;
746 for (size_t i = 0; i < num_threads; ++i) {
747 ts.emplace_back([&]() {
751 for (size_t n = 0; n < num_iters; ++n) {
765 // Repro for a bug when iterator didn't skip empty submaps.
766 TEST(Ahm, iterator_skips_empty_submaps) {
767 AtomicHashMap<uint64_t, uint64_t>::Config config;
768 config.growthFactor = 1;
770 AtomicHashMap<uint64_t, uint64_t> map(1, config);
778 auto it = map.find(1);
780 ASSERT_NE(map.end(), it);
781 ASSERT_EQ(1, it->first);
782 ASSERT_EQ(1, it->second);
786 ASSERT_NE(map.end(), it);
787 ASSERT_EQ(3, it->first);
788 ASSERT_EQ(3, it->second);
791 ASSERT_EQ(map.end(), it);
796 void loadGlobalAha() {
797 std::cout << "loading global AHA with " << FLAGS_numThreads
799 uint64_t start = nowInUsec();
800 globalAHA = AHArrayT::create(maxBMElements, config);
801 numOpsPerThread = FLAGS_numBMElements / FLAGS_numThreads;
802 CHECK_EQ(0, FLAGS_numBMElements % FLAGS_numThreads) <<
803 "kNumThreads must evenly divide kNumInserts.";
804 runThreads(insertThreadArr);
805 uint64_t elapsed = nowInUsec() - start;
806 std::cout << " took " << elapsed / 1000 << " ms (" <<
807 (elapsed * 1000 / FLAGS_numBMElements) << " ns/insert).\n";
808 EXPECT_EQ(globalAHA->size(), FLAGS_numBMElements);
811 void loadGlobalAhm() {
812 std::cout << "loading global AHM with " << FLAGS_numThreads
814 uint64_t start = nowInUsec();
815 globalAHM.reset(new AHMapT(maxBMElements, config));
816 numOpsPerThread = FLAGS_numBMElements / FLAGS_numThreads;
817 runThreads(insertThread);
818 uint64_t elapsed = nowInUsec() - start;
819 std::cout << " took " << elapsed / 1000 << " ms (" <<
820 (elapsed * 1000 / FLAGS_numBMElements) << " ns/insert).\n";
821 EXPECT_EQ(globalAHM->size(), FLAGS_numBMElements);
824 void loadGlobalQPAhm() {
825 std::cout << "loading global QPAHM with " << FLAGS_numThreads
827 uint64_t start = nowInUsec();
828 globalQPAHM.reset(new QPAHMapT(maxBMElements, qpConfig));
829 numOpsPerThread = FLAGS_numBMElements / FLAGS_numThreads;
830 runThreads(qpInsertThread);
831 uint64_t elapsed = nowInUsec() - start;
832 std::cout << " took " << elapsed / 1000 << " ms (" <<
833 (elapsed * 1000 / FLAGS_numBMElements) << " ns/insert).\n";
834 EXPECT_EQ(globalQPAHM->size(), FLAGS_numBMElements);
839 BENCHMARK(st_aha_find, iters) {
840 CHECK_LE(iters, FLAGS_numBMElements);
841 for (size_t i = 0; i < iters; i++) {
842 KeyT key = randomizeKey(i);
843 folly::doNotOptimizeAway(globalAHA->find(key)->second);
847 BENCHMARK(st_ahm_find, iters) {
848 CHECK_LE(iters, FLAGS_numBMElements);
849 for (size_t i = 0; i < iters; i++) {
850 KeyT key = randomizeKey(i);
851 folly::doNotOptimizeAway(globalAHM->find(key)->second);
855 BENCHMARK(st_qpahm_find, iters) {
856 CHECK_LE(iters, FLAGS_numBMElements);
857 for (size_t i = 0; i < iters; i++) {
858 KeyT key = randomizeKey(i);
859 folly::doNotOptimizeAway(globalQPAHM->find(key)->second);
863 BENCHMARK_DRAW_LINE()
865 BENCHMARK(mt_ahm_miss, iters) {
866 CHECK_LE(iters, FLAGS_numBMElements);
867 numOpsPerThread = iters / FLAGS_numThreads;
868 runThreads([](void* jj) -> void* {
869 int64_t j = (int64_t) jj;
870 while (!runThreadsCreatedAllThreads.load());
871 for (int i = 0; i < numOpsPerThread; ++i) {
872 KeyT key = i + j * numOpsPerThread * 100;
873 folly::doNotOptimizeAway(globalAHM->find(key) == globalAHM->end());
879 BENCHMARK(mt_qpahm_miss, iters) {
880 CHECK_LE(iters, FLAGS_numBMElements);
881 numOpsPerThread = iters / FLAGS_numThreads;
882 runThreads([](void* jj) -> void* {
883 int64_t j = (int64_t) jj;
884 while (!runThreadsCreatedAllThreads.load());
885 for (int i = 0; i < numOpsPerThread; ++i) {
886 KeyT key = i + j * numOpsPerThread * 100;
887 folly::doNotOptimizeAway(globalQPAHM->find(key) == globalQPAHM->end());
893 BENCHMARK(st_ahm_miss, iters) {
894 CHECK_LE(iters, FLAGS_numBMElements);
895 for (size_t i = 0; i < iters; i++) {
896 KeyT key = randomizeKey(i + iters * 100);
897 folly::doNotOptimizeAway(globalAHM->find(key) == globalAHM->end());
901 BENCHMARK(st_qpahm_miss, iters) {
902 CHECK_LE(iters, FLAGS_numBMElements);
903 for (size_t i = 0; i < iters; i++) {
904 KeyT key = randomizeKey(i + iters * 100);
905 folly::doNotOptimizeAway(globalQPAHM->find(key) == globalQPAHM->end());
909 BENCHMARK(mt_ahm_find_insert_mix, iters) {
910 CHECK_LE(iters, FLAGS_numBMElements);
911 numOpsPerThread = iters / FLAGS_numThreads;
912 runThreads([](void* jj) -> void* {
913 int64_t j = (int64_t) jj;
914 while (!runThreadsCreatedAllThreads.load());
915 for (int i = 0; i < numOpsPerThread; ++i) {
916 if (i % 128) { // ~1% insert mix
917 KeyT key = randomizeKey(i + j * numOpsPerThread);
918 folly::doNotOptimizeAway(globalAHM->find(key)->second);
920 KeyT key = randomizeKey(i + j * numOpsPerThread * 100);
921 globalAHM->insert(key, genVal(key));
929 BENCHMARK(mt_qpahm_find_insert_mix, iters) {
930 CHECK_LE(iters, FLAGS_numBMElements);
931 numOpsPerThread = iters / FLAGS_numThreads;
932 runThreads([](void* jj) -> void* {
933 int64_t j = (int64_t) jj;
934 while (!runThreadsCreatedAllThreads.load());
935 for (int i = 0; i < numOpsPerThread; ++i) {
936 if (i % 128) { // ~1% insert mix
937 KeyT key = randomizeKey(i + j * numOpsPerThread);
938 folly::doNotOptimizeAway(globalQPAHM->find(key)->second);
940 KeyT key = randomizeKey(i + j * numOpsPerThread * 100);
941 globalQPAHM->insert(key, genVal(key));
948 BENCHMARK(mt_aha_find, iters) {
949 CHECK_LE(iters, FLAGS_numBMElements);
950 numOpsPerThread = iters / FLAGS_numThreads;
951 runThreads([](void* jj) -> void* {
952 int64_t j = (int64_t) jj;
953 while (!runThreadsCreatedAllThreads.load());
954 for (int i = 0; i < numOpsPerThread; ++i) {
955 KeyT key = randomizeKey(i + j * numOpsPerThread);
956 folly::doNotOptimizeAway(globalAHA->find(key)->second);
962 BENCHMARK(mt_ahm_find, iters) {
963 CHECK_LE(iters, FLAGS_numBMElements);
964 numOpsPerThread = iters / FLAGS_numThreads;
965 runThreads([](void* jj) -> void* {
966 int64_t j = (int64_t) jj;
967 while (!runThreadsCreatedAllThreads.load());
968 for (int i = 0; i < numOpsPerThread; ++i) {
969 KeyT key = randomizeKey(i + j * numOpsPerThread);
970 folly::doNotOptimizeAway(globalAHM->find(key)->second);
976 BENCHMARK(mt_qpahm_find, iters) {
977 CHECK_LE(iters, FLAGS_numBMElements);
978 numOpsPerThread = iters / FLAGS_numThreads;
979 runThreads([](void* jj) -> void* {
980 int64_t j = (int64_t) jj;
981 while (!runThreadsCreatedAllThreads.load());
982 for (int i = 0; i < numOpsPerThread; ++i) {
983 KeyT key = randomizeKey(i + j * numOpsPerThread);
984 folly::doNotOptimizeAway(globalQPAHM->find(key)->second);
991 BENCHMARK(st_baseline_modulus_and_random, iters) {
992 for (size_t i = 0; i < iters; ++i) {
993 k = randomizeKey(i) % iters;
997 // insertions go last because they reset the map
999 BENCHMARK(mt_ahm_insert, iters) {
1001 globalAHM.reset(new AHMapT(int(iters * LF), config));
1002 numOpsPerThread = iters / FLAGS_numThreads;
1004 runThreads(insertThread);
1007 BENCHMARK(mt_qpahm_insert, iters) {
1009 globalQPAHM.reset(new QPAHMapT(int(iters * LF), qpConfig));
1010 numOpsPerThread = iters / FLAGS_numThreads;
1012 runThreads(qpInsertThread);
1015 BENCHMARK(st_ahm_insert, iters) {
1016 folly::BenchmarkSuspender susp;
1017 std::unique_ptr<AHMapT> ahm(new AHMapT(int(iters * LF), config));
1020 for (size_t i = 0; i < iters; i++) {
1021 KeyT key = randomizeKey(i);
1022 ahm->insert(key, genVal(key));
1026 BENCHMARK(st_qpahm_insert, iters) {
1027 folly::BenchmarkSuspender susp;
1028 std::unique_ptr<QPAHMapT> ahm(new QPAHMapT(int(iters * LF), qpConfig));
1031 for (size_t i = 0; i < iters; i++) {
1032 KeyT key = randomizeKey(i);
1033 ahm->insert(key, genVal(key));
1037 void benchmarkSetup() {
1038 config.maxLoadFactor = FLAGS_maxLoadFactor;
1039 qpConfig.maxLoadFactor = FLAGS_maxLoadFactor;
1040 configRace.maxLoadFactor = 0.5;
1041 int numCores = sysconf(_SC_NPROCESSORS_ONLN);
1045 string numIters = folly::to<string>(
1046 std::min(1000000, int(FLAGS_numBMElements)));
1048 gflags::SetCommandLineOptionWithMode(
1049 "bm_max_iters", numIters.c_str(), gflags::SET_FLAG_IF_DEFAULT
1051 gflags::SetCommandLineOptionWithMode(
1052 "bm_min_iters", numIters.c_str(), gflags::SET_FLAG_IF_DEFAULT
1054 string numCoresStr = folly::to<string>(numCores);
1055 gflags::SetCommandLineOptionWithMode(
1056 "numThreads", numCoresStr.c_str(), gflags::SET_FLAG_IF_DEFAULT
1059 std::cout << "\nRunning AHM benchmarks on machine with " << numCores
1060 << " logical cores.\n"
1061 " num elements per map: " << FLAGS_numBMElements << "\n"
1062 << " num threads for mt tests: " << FLAGS_numThreads << "\n"
1063 << " AHM load factor: " << FLAGS_targetLoadFactor << "\n\n";
1066 int main(int argc, char** argv) {
1067 testing::InitGoogleTest(&argc, argv);
1068 gflags::ParseCommandLineFlags(&argc, &argv, true);
1069 auto ret = RUN_ALL_TESTS();
1070 if (!ret && FLAGS_benchmark) {
1072 folly::runBenchmarks();
1078 loading global AHA with 8 threads...
1079 took 487 ms (40 ns/insert).
1080 loading global AHM with 8 threads...
1081 took 478 ms (39 ns/insert).
1082 loading global QPAHM with 8 threads...
1083 took 478 ms (39 ns/insert).
1085 Running AHM benchmarks on machine with 24 logical cores.
1086 num elements per map: 12000000
1087 num threads for mt tests: 24
1088 AHM load factor: 0.75
1090 ============================================================================
1091 folly/test/AtomicHashMapTest.cpp relative time/iter iters/s
1092 ============================================================================
1093 st_aha_find 92.63ns 10.80M
1094 st_ahm_find 107.78ns 9.28M
1095 st_qpahm_find 90.69ns 11.03M
1096 ----------------------------------------------------------------------------
1097 mt_ahm_miss 2.09ns 477.36M
1098 mt_qpahm_miss 1.37ns 728.82M
1099 st_ahm_miss 241.07ns 4.15M
1100 st_qpahm_miss 223.17ns 4.48M
1101 mt_ahm_find_insert_mix 8.05ns 124.24M
1102 mt_qpahm_find_insert_mix 9.10ns 109.85M
1103 mt_aha_find 6.82ns 146.68M
1104 mt_ahm_find 7.95ns 125.77M
1105 mt_qpahm_find 6.81ns 146.83M
1106 st_baseline_modulus_and_random 6.02ns 166.03M
1107 mt_ahm_insert 14.29ns 69.97M
1108 mt_qpahm_insert 11.68ns 85.61M
1109 st_ahm_insert 125.39ns 7.98M
1110 st_qpahm_insert 128.76ns 7.77M
1111 ============================================================================