Repository navigation
Expand file tree
/
Copy pathmartin_bench.cpp
More file actions
3359 lines (2960 loc) · 103 KB
/
Copy pathmartin_bench.cpp
File metadata and controls
3359 lines (2960 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//#define FIB_HASH 7
#pragma GCC diagnostic ignored "-Wunused-result"
#include "util.h"
#include <sstream>
#include <fstream>
#include <numeric>
#include <algorithm>
#ifndef _WIN32
#include <sys/resource.h>
#endif
// ============================================================================
// Benchmark Configuration and Output Support
// ============================================================================
// Output format options
enum class OutputFormat {
Text, // Default printf output
CSV, // CSV format for analysis
JSON // JSON format for visualization
};
// Benchmark configuration structure
struct BenchConfig {
size_t warmup_iterations = 1000; // Warmup iterations before timing
int benchmark_iterations = 1; // Number of benchmark runs (for averaging)
float max_load_factor = 7.0f / 8; // Default max load factor
bool enable_reserve = true; // Whether to reserve before insert
OutputFormat output_format = OutputFormat::Text;
std::string output_file = ""; // Output file path (empty = stdout)
};
// Benchmark result structure
struct BenchResult {
std::string test_name;
std::string hash_map_name;
double time_sec;
double time_stddev = 0.0; // Standard deviation (if multiple runs)
size_t operations = 0;
double throughput = 0.0; // Operations per second
float load_factor = 0.0f;
size_t map_size = 0;
};
// Global configuration
static BenchConfig g_config;
static std::vector<BenchResult> g_results;
// Output formatter
class ResultOutput {
public:
static void output_text(const BenchResult& r) {
if (r.time_stddev > 0) {
printf(" %20s: %.3f s (stddev=%.3f) ops=%zu throughput=%.2f M/s\n", r.hash_map_name.c_str(), r.time_sec,
r.time_stddev, r.operations, r.throughput / 1000000.0);
} else {
printf(" %20s: %.3f s ops=%zu throughput=%.2f M/s\n", r.hash_map_name.c_str(), r.time_sec, r.operations,
r.throughput / 1000000.0);
}
}
static void output_csv_header() { printf("Test,HashMap,Time,StdDev,Operations,Throughput,LoadFactor,MapSize\n"); }
static void output_csv(const BenchResult& r) {
printf("%s,%s,%.6f,%.6f,%zu,%.2f,%.2f,%zu\n", r.test_name.c_str(), r.hash_map_name.c_str(), r.time_sec,
r.time_stddev, r.operations, r.throughput, r.load_factor, r.map_size);
}
static void output_json_header() { printf("[\n"); }
static void output_json(const BenchResult& r, bool is_last) {
printf(" {\n");
printf(" \"test\": \"%s\",\n", r.test_name.c_str());
printf(" \"hashmap\": \"%s\",\n", r.hash_map_name.c_str());
printf(" \"time\": %.6f,\n", r.time_sec);
printf(" \"stddev\": %.6f,\n", r.time_stddev);
printf(" \"operations\": %zu,\n", r.operations);
printf(" \"throughput\": %.2f,\n", r.throughput);
printf(" \"load_factor\": %.2f,\n", r.load_factor);
printf(" \"map_size\": %zu\n", r.map_size);
printf(" }%s\n", is_last ? "" : ",");
}
static void output_json_footer() { printf("]\n"); }
static void output_all(const std::vector<BenchResult>& results, OutputFormat format) {
if (format == OutputFormat::CSV) {
output_csv_header();
for (const auto& r : results) {
output_csv(r);
}
} else if (format == OutputFormat::JSON) {
output_json_header();
for (size_t i = 0; i < results.size(); ++i) {
output_json(results[i], i == results.size() - 1);
}
output_json_footer();
} else {
for (const auto& r : results) {
output_text(r);
}
}
}
};
// Warmup helper function
template <typename HMAP, typename RNG> static void do_warmup(HMAP& hmap, RNG& rng, size_t iterations) {
for (size_t i = 0; i < iterations; ++i) {
hmap[static_cast<int>(rng())] = 0;
}
hmap.clear();
}
//#define EMH_ITER_SAFE 1
//#include "wyhash.h"
//#define EMH_STATIS 1
//#define ET 1
//#define EMH_WYHASH64 1
//#define HOOD_HASH 1
//
//#define EMH_PACK_TAIL 16
//#define EMH_HIGH_LOAD 123456
//#define EMH_STATIS 1234567
#if CK_HMAP
#include "ck/Common/HashTable/HashMap.h"
#endif
#include "emhash/hash_table5.hpp"
#include "emhash/hash_table6.hpp"
#include "emhash/hash_table7.hpp"
#include "emhash/hash_table8.hpp"
#if HAVE_BOOST
#include <boost/unordered/unordered_flat_map.hpp>
#endif
//#define HAVE_EXCALIBUR 1
//#define HAVE_INDIVI 1
#if HAVE_EXCALIBUR
// https://github.com/SergeyMakeev/ExcaliburHash
#include "ExcaliburHash/ExcaliburHash.h"
#endif
// https://github.com/gaujay/indivi_collection
#if HAVE_INDIVI
#include "indivi/flat_umap.h"
#include "indivi/flat_wmap.h"
#endif
// #define EMH_QUADRATIC 1
// #define EMH_STATIS 123456
// #define AVX2_EHASH 1
// #define EMH_PSL_LINEAR 1
#include "emilib/emihmap1.hpp"
#include "emilib/emihmap2.hpp"
#include "emilib/emihmap3.hpp"
#include "emilib/emihmap4.hpp"
#include "martin/robin_hood.h"
#if CXX17
#include "martin/unordered_dense.h"
#endif
//#include "FHashTable/fhash_table.h"
#if ET
#include "phmap/phmap.h"
#include "tsl/robin_map.h"
#if X86_64
#include "ska/flat_hash_map.hpp"
#include "hrd/hash_set_m.h"
#endif
#endif
#if FOLLY_F14
#include "folly/container/F14Map.h"
#endif
static const uint64_t RND = (uint64_t)getus();
static float max_lf = 7.0f / 8;
static std::map<std::string_view, std::string_view> show_name = {
{"emhash7", "emhash7"},
{"emhash8", "emhash8"},
// {"emhash5", "emhash5"},
{"emhash6", "emhash6"},
{"emilib", "emilib1"},
{"emilib2", "emilib2"},
{"emilib3", "emilib3"},
{"emilib4", "emilib4"},
#if HAVE_BOOST
{"boost", "boost flat"},
#endif
#if HAVE_EXCALIBUR
{"Excalibur", "excalibur"},
#endif
#if HAVE_INDIVI
//{"flat_u", "indivi_umap"},
{"flat_w", "indivi_wmap"},
#endif
#if CK_HMAP
{"HashMapCell", "ck_hashmap"},
{"HashMapTable", "ck_hashmap"},
#endif
// {"fhash_table", "fht"},
// {"ankerl", "martin dense"},
#if QC_HASH
{"qc", "qchash"},
{"fph", "fph"},
#endif
#if ABSL_HMAP
{"absl", "absl flat"},
#endif
#if CXX20
{"rigtorp", "rigtorp"},
{"jg", "jg_dense"},
#endif
#if ET
{"hrd_m", "hrdm"},
{"phmap", "phmap flat"},
{"robin_hood", "martin flat"},
// {"folly", "f14_vector"},
#if ET > 1
{"robin_map", "tessil robin"},
{"ska", "skarupk flat"},
#endif
#endif
};
static const char* find_hash(const std::string& map_name) {
if (map_name.find("emilib2") < 10)
return show_name.count("emilib2") ? show_name["emilib2"].data() : nullptr;
if (map_name.find("emilib3") < 10)
return show_name.count("emilib3") ? show_name["emilib3"].data() : nullptr;
if (map_name.find("emilib4") < 10)
return show_name.count("emilib4") ? show_name["emilib4"].data() : nullptr;
if (map_name.find("HashMapCell") < 30)
return show_name.count("HashMapCell") ? show_name["HashMapCell"].data() : nullptr;
if (map_name.find("HashMapTable") < 30)
return show_name.count("HashMapTable") ? show_name["HashMapTable"].data() : nullptr;
if (map_name.find("flat_u") < 30)
return show_name.count("flat_u") ? show_name["flat_u"].data() : nullptr;
if (map_name.find("flat_w") < 30)
return show_name.count("flat_w") ? show_name["flat_w"].data() : nullptr;
for (const auto& kv : show_name) {
if (map_name.find(kv.first) < 10)
return kv.second.data();
}
return nullptr;
}
#ifndef RT
#define RT 2 // 2 wyrand 1 sfc64 3 RomuDuoJr 4 Lehmer64 5 mt19937_64
#endif
#if RT == 1
#define MRNG sfc64
#elif RT == 2
#define MRNG WyRand
#elif RT == 3
#define MRNG RomuDuoJr
#else
#define MRNG Lehmer64
#endif
// this is probably the fastest high quality 64bit random number generator that exists.
// Implements Small Fast Counting v4 RNG from PractRand.
class sfc64 {
public:
using result_type = uint64_t;
// no copy ctors so we don't accidentally get the same random again
sfc64(sfc64 const&) = delete;
sfc64& operator=(sfc64 const&) = delete;
sfc64(sfc64&&) = default;
sfc64& operator=(sfc64&&) = default;
sfc64(std::array<uint64_t, 4> const& state) : m_a(state[0]), m_b(state[1]), m_c(state[2]), m_counter(state[3]) {}
static constexpr uint64_t(min)() { return (std::numeric_limits<uint64_t>::min)(); }
static constexpr uint64_t(max)() { return (std::numeric_limits<uint64_t>::max)(); }
sfc64() : sfc64(UINT64_C(0x853c49e6748fea9b)) {}
sfc64(uint64_t seed) : m_a(seed), m_b(seed), m_c(seed), m_counter(1) {
for (int i = 0; i < 12; ++i) {
operator()();
}
}
void seed() { *this = sfc64{std::random_device{}()}; }
uint64_t operator()() noexcept {
auto const tmp = m_a + m_b + m_counter++;
m_a = m_b ^ (m_b >> right_shift);
m_b = m_c + (m_c << left_shift);
m_c = rotl(m_c, (int)rotation) + tmp;
return tmp;
}
// this is a bit biased, but for our use case that's not important.
uint64_t operator()(uint64_t boundExcluded) noexcept {
#ifdef __SIZEOF_INT128__
return static_cast<uint64_t>(
(static_cast<unsigned __int128>(operator()()) * static_cast<unsigned __int128>(boundExcluded)) >> 64u);
#elif _WIN32
uint64_t high;
uint64_t a = operator()();
_umul128(a, boundExcluded, &high);
return high;
#endif
}
std::array<uint64_t, 4> state() const {
return {m_a, m_b, m_c, m_counter};
}
void state(std::array<uint64_t, 4> const& s) {
m_a = s[0];
m_b = s[1];
m_c = s[2];
m_counter = s[3];
}
private:
template <typename T> T rotl(T const x, uint32_t k) {
return (x << k) | (x >> (8 * sizeof(T) - k));
}
static constexpr int rotation = 24;
static constexpr int right_shift = 11;
static constexpr int left_shift = 3;
uint64_t m_a;
uint64_t m_b;
uint64_t m_c;
uint64_t m_counter;
};
static inline double now2sec() {
#if _WIN32
FILETIME ft;
#if _WIN32_WINNT >= 0x0602
GetSystemTimePreciseAsFileTime(&ft);
#else
GetSystemTimeAsFileTime(&ft);
#endif /* Windows 8 */
/* `t := (low + high * 0x1p32) / 10000` */
double t = (double)ft.dwLowDateTime + (double)ft.dwHighDateTime * 0x1p32;
/* 11644473600000 is number of milliseconds from 1601-01-01T00:00:00Z
* (the NT epoch) to 1970-01-01T00:00:00Z (the Unix Epoch). */
return (t / 10000'000 - 11644473600);
#elif __linux__
struct rusage rup;
getrusage(RUSAGE_SELF, &rup);
long sec = rup.ru_utime.tv_sec + rup.ru_stime.tv_sec;
long usec = rup.ru_utime.tv_usec + rup.ru_stime.tv_usec;
return (double)sec + (double)usec / 1000000.0;
#elif __unix__
struct timeval start;
gettimeofday(&start, NULL);
return start.tv_sec + start.tv_usec / 1000000.0;
#else
auto tp = std::chrono::steady_clock::now().time_since_epoch();
return std::chrono::duration_cast<std::chrono::microseconds>(tp).count() / 1000000.0;
#endif
}
template <typename HMAP, typename Key, typename Value>
auto has_insert_unique(int)
-> decltype(std::declval<HMAP>().insert_unique(std::declval<Key>(), std::declval<Value>()), std::true_type{});
template <typename HMAP, typename Key, typename Value> std::false_type has_insert_unique(...) {
return std::false_type{};
}
template <typename HMAP, typename Key, typename Value>
constexpr bool has_insert_unique_v = decltype(has_insert_unique<HMAP, Key, Value>(0))::value;
template <typename HMAP> static void bench_insert(HMAP& hmap) {
auto map_name = find_hash(typeid(HMAP).name());
if (!map_name)
return;
printf(" %20s:\n", map_name);
#if X86_64 || __MAC__
uint32_t maxn = 1000000;
#else
uint32_t maxn = 1000000 / 5;
#endif
hmap.max_load_factor(g_config.max_load_factor);
for (int i = 0; i < 3; i++) {
auto nows = now2sec();
{
auto RNDI = (uint64_t)RND + 15ull + (uint64_t)i;
// Warmup phase - warm up cache before actual benchmark
if (g_config.warmup_iterations > 0) {
MRNG warmup_rng(RNDI + 1000);
do_warmup(hmap, warmup_rng, g_config.warmup_iterations);
}
{
if (g_config.enable_reserve && RND % 2 == 0)
hmap.reserve(maxn / 2);
auto ts = now2sec();
MRNG rng(RNDI);
for (size_t n = 0; n < maxn; ++n)
if constexpr (has_insert_unique_v<HMAP, int, int>)
hmap.insert_unique(static_cast<int>(rng()), 0);
else
hmap[static_cast<int>(rng())];
printf("\t\t (lf=%.2f) insert %.2f", hmap.load_factor(), now2sec() - ts);
fflush(stdout);
// Record result for CSV/JSON output
if (g_config.output_format != OutputFormat::Text) {
BenchResult r;
r.test_name = "insert";
r.hash_map_name = map_name;
r.time_sec = now2sec() - ts;
r.operations = maxn;
r.throughput = maxn / r.time_sec;
r.load_factor = hmap.load_factor();
r.map_size = hmap.size();
g_results.push_back(r);
}
}
{
auto ts = now2sec();
MRNG rng(RNDI);
for (size_t n = 0; n < maxn * 9 / 10; ++n)
hmap.erase(static_cast<int>(rng()));
printf(", remove 90%% %.2f", now2sec() - ts);
fflush(stdout);
assert(hmap.size() == 0);
// Record result
if (g_config.output_format != OutputFormat::Text) {
BenchResult r;
r.test_name = "erase_90pct";
r.hash_map_name = map_name;
r.time_sec = now2sec() - ts;
r.operations = maxn * 9 / 10;
r.throughput = r.operations / r.time_sec;
g_results.push_back(r);
}
}
{
auto ts = now2sec();
MRNG rng(RNDI + 1);
for (size_t n = 0; n < maxn; ++n)
if constexpr (has_insert_unique_v<HMAP, int, int>)
hmap.insert_unique(static_cast<int>(rng()), 0);
else
hmap.emplace(static_cast<int>(rng()), 0);
printf(", reinsert %.2f", now2sec() - ts);
// Record result
if (g_config.output_format != OutputFormat::Text) {
BenchResult r;
r.test_name = "reinsert";
r.hash_map_name = map_name;
r.time_sec = now2sec() - ts;
r.operations = maxn;
r.throughput = maxn / r.time_sec;
r.load_factor = hmap.load_factor();
r.map_size = hmap.size();
g_results.push_back(r);
}
}
{
auto ts = now2sec();
hmap.clear();
printf(", clear %.3f", now2sec() - ts);
}
}
printf(" %dM, total %2.2f s\n", int(maxn / 1000000), now2sec() - nows);
maxn *= 10;
}
}
template <typename HMAP, bool unique = false> static void bench_AccidentallyQuadratic() {
auto map_name = find_hash(typeid(HMAP).name());
if (!map_name)
return;
printf(" %20s:", map_name);
auto nows = now2sec();
sfc64 rng(12345);
HMAP hmap;
for (size_t n = 0; n < 10'000'000; ++n) {
hmap[static_cast<int>(rng())];
}
assert(9988513 == hmap.size());
// bench.beginMeasure("iterate");
uint64_t sum = 0;
for (auto const& kv : hmap) {
sum += (uint64_t)kv.first + (uint64_t)kv.second;
}
if (sum != UINT64_C(18446739465311920326))
puts("error\n");
#if CXX17
// bench.beginMeasure("iterate & copy");
HMAP map2;
for (auto const& kv : hmap) {
if constexpr (unique)
map2.insert_unique(kv.first, kv.second);
else
map2.emplace(kv.first, kv.second);
}
assert(hmap.size() == map2.size());
#endif
printf(" time %2.2f s\n", now2sec() - nows);
}
template <typename HMAP> static void bench_InsertEraseBegin() {
auto map_name = find_hash(typeid(HMAP).name());
if (!map_name)
return;
printf(" %20s:", map_name);
size_t max_n = 100000;
auto nows = now2sec();
for (uint64_t i = 0; i < 3; ++i) {
auto starts = now2sec();
HMAP hmap;
MRNG rng(987654321ull + i * i * i);
// benchmark randomly inserting & erasing begin
for (size_t j = 0; j < max_n / 5; ++j)
hmap.emplace((int64_t)rng(), 0);
for (size_t j = 0; j < max_n; ++j) {
hmap.erase(hmap.begin());
hmap.emplace((int64_t)rng(), 0);
}
printf("\n\t\t %.2f loadf = %.2f mapsize = %d time %2.2f s", ((double)max_n / 1000000.0),
hmap.load_factor(), (int)hmap.size(), now2sec() - starts);
max_n *= 5;
}
printf(", total %2.2f s\n", now2sec() - nows);
}
template <typename HMAP> static void bench_InsertEraseContinue() {
auto map_name = find_hash(typeid(HMAP).name());
if (!map_name)
return;
printf(" %20s:", map_name);
size_t max_n = 400000;
auto nows = now2sec();
for (uint64_t i = 0; i < 3; ++i) {
auto starts = now2sec();
HMAP hmap;
// hmap.reserve((std::size_t)(max_n * .));
MRNG rng(2345ull + i * i * i);
// benchmark randomly inserting & erasing begin
for (size_t j = 0; j < max_n / 3; ++j)
hmap.emplace((int)rng(), 0);
auto key = hmap.begin()->first;
for (size_t j = max_n; j > 0; j--) {
auto it = hmap.find(key);
if (it == hmap.end()) {
it = hmap.begin();
key = it->first;
}
if constexpr (std::is_void_v<decltype(hmap.erase(it))>) {
hmap.erase(it);
if (++it != hmap.end())
key = it->first;
} else {
it = hmap.erase(it);
if (it != hmap.end())
key = it->first;
}
hmap.emplace((int)rng(), 0);
}
printf("\n\t\t %.2f loadf = %.2f mapsize = %d time %.2f", ((double)max_n / 1000000.0),
hmap.load_factor(), (int)hmap.size(), now2sec() - starts);
max_n *= 7;
}
printf(", total %2.2f s\n", now2sec() - nows);
}
template <typename T> struct as_bits_t { T value; };
template <typename T> as_bits_t<T> as_bits(T value) {
return as_bits_t<T>{value};
}
template <typename T> std::ostream& operator<<(std::ostream& os, as_bits_t<T> const& t) {
os << std::bitset<sizeof(t.value) * 8>(t.value);
return os;
}
template <class RandomIt, class URBG> static void rshuffle(RandomIt first, RandomIt last, URBG&& g) {
typedef typename std::iterator_traits<RandomIt>::difference_type diff_t;
typedef std::uniform_int_distribution<diff_t> distr_t;
typedef typename distr_t::param_type param_t;
distr_t D;
diff_t n = last - first;
for (diff_t i = n - 1; i > 0; --i) {
using std::swap;
swap(first[i], first[D(g, param_t(0, i))]);
}
}
template <class ForwardIt, class T> static void iotas(ForwardIt first, ForwardIt last, T value) {
while (first != last) {
*first++ = value;
++value;
}
}
template <typename HMAP> static void bench_randomInsertErase(HMAP& hmap) {
auto map_name = find_hash(typeid(HMAP).name());
if (!map_name)
return;
printf(" %20s:", map_name);
auto nows = now2sec();
double erase1 = 0, erase2 = 0;
if (1) {
uint32_t min_n = 1 << 20;
uint32_t max_loop = min_n << 5;
hmap.max_load_factor(max_lf);
for (uint64_t j = 0; j < 5; ++j) {
const uint64_t rndj = RND + 6 + j;
MRNG rng(rndj);
MRNG rng2(rndj);
// each iteration, set 4 new random bits.
// std::cout << (i + 1) << ". " << as_bits(bitMask) << std::endl;
auto maxn = min_n * (50 + j * 9) / 100;
for (size_t i = 0; i < maxn / 8; ++i) {
hmap.emplace(rng(), 0);
}
// auto ts = now2sec();
maxn = max_loop * 10 / (10 + 4 * j);
// benchmark randomly inserting & erasing
for (size_t i = 0; i < maxn; ++i) {
hmap.emplace(rng(), 0);
hmap.erase(rng2());
}
// printf(" %8u %2d M time %.3f s hmap size %8d loadf = %.2f\n",
// maxn, int(min_n / 1000000), now2sec() - ts, (int)hmap.size(), hmap.load_factor());
min_n *= 2;
hmap.clear();
}
erase1 = now2sec() - nows;
}
{
HMAP map2;
map2.max_load_factor(max_lf);
std::vector<int> bits(64, 0);
iotas(bits.begin(), bits.end(), 0);
sfc64 rng(999);
#if 0
for (auto &v : bits) v = rng();
#else
rshuffle(bits.begin(), bits.end(), rng);
#endif
nows = now2sec();
uint64_t bitMask = 0;
auto bitsIt = bits.begin();
// size_t const expectedFinalSizes[] = {7, 127, 2084, 32722, 524149, 8367491};
size_t const max_n = 20000000;
for (int i = 0; i < 6; ++i) {
for (int b = 0; b < 4; ++b) {
bitMask |= UINT64_C(1) << *bitsIt++;
}
// auto ts = now2sec();
for (size_t j = 0; j < max_n; ++j) {
map2.emplace(rng() & bitMask, 0);
map2.erase(rng() & bitMask);
}
// printf(" %02d bits %2d M time %.3f s hmap size %d loadf = %.2f\n",
// int(std::bitset<64>(bitMask).count()), int(max_n / 1000000), now2sec() - ts,
// (int)map2.size(), map2.load_factor());
}
erase2 = now2sec() - nows;
}
printf(" erase time %.2f + %.2f, total %2.2f s\n", erase1, erase2, erase1 + erase2);
}
template <typename HMAP> static void bench_CreateInsert() {
auto map_name = find_hash(typeid(HMAP).name());
if (!map_name)
return;
printf(" %20s:", map_name);
const std::array<size_t, 7> counts = {200, 2000, 2000, 20000, 200000, 2000000, 20000000};
MRNG rng(213 + RND);
auto nows = now2sec(), erase1 = 0.;
for (size_t i = 0; i < counts.size(); ++i) {
size_t count = counts[i];
size_t repeats = counts.back() / count;
[[maybe_unused]] size_t res = 0;
HMAP hmap;
for (size_t j = 0; j < repeats; ++j) {
for (size_t n = 0; n < count; ++n)
hmap[static_cast<int>(rng())];
res += (size_t)hmap.size();
}
}
erase1 = now2sec() - nows;
nows = now2sec();
MRNG rng2(213 + RND);
for (size_t i = 0; i < counts.size(); ++i) {
size_t count = counts[i];
size_t repeats = counts.back() / count;
[[maybe_unused]] size_t res = 0;
HMAP hmap;
for (size_t j = 0; j < repeats; ++j) {
for (size_t n = 0; n < count; ++n)
hmap[static_cast<int>(rng2())];
res += (size_t)hmap.size();
hmap.clear();
}
}
assert(res);
auto erase2 = now2sec() - nows;
printf(" CreateInsert/InsertCreate %2.2f + %2.2f, total %2.2f s\n", erase1, erase2, erase1 + erase2);
}
static inline uint32_t udb_hash32(uint32_t key) {
#if 0
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return key;
#else
uint64_t x = key;
x ^= x >> 30;
x *= 0xbf58476d1ce4e5b9ULL;
x ^= x >> 27;
x *= 0x94d049bb133111ebULL;
x ^= x >> 31;
return (uint32_t)x;
#endif
}
static inline uint32_t udb_get_key(const uint32_t n, const uint32_t x) {
#if 0
return udb_hash32(x % (n>>2));
#else
return (uint32_t)((x % (n >> 2)) * 0x45D9F3B);
#endif
}
static uint64_t splitmix64(uint64_t& x) {
uint64_t z = (x += 0x9e3779b97f4a7c15ULL);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
return z ^ (z >> 31);
}
struct Hash32 {
// using is_avalanching = void;
inline size_t operator()(const uint32_t x) const { return x; }
};
const static uint32_t x0 = (uint32_t)getus();
const static bool is_del = (x0 % 2 == 0);
template <typename HMAP> static void bench_udb3() {
auto map_name = find_hash(typeid(HMAP).name());
if (!map_name)
return;
printf(" %20s:", map_name);
const auto nows = now2sec();
constexpr uint32_t n_cp = 11, N = 80000000, n0 = 10000000;
constexpr uint32_t step = (N - n0) / (n_cp - 1);
HMAP h;
uint64_t z = 0, x = x0;
for (uint32_t j = 0, i = 0, n = n0; j < n_cp; ++j, n += step) {
for (; i < n; ++i) {
const uint64_t y = splitmix64(x);
const uint32_t key = udb_get_key(n, (uint32_t)y);
if (is_del) {
auto p = h.emplace(key, i);
if (!p.second)
h.erase(p.first);
z += p.second;
} else {
z += ++h[key];
}
}
}
printf(" z[%d] = %d loadf = %.2f, total %2.2f s\n", is_del, (int)z, h.load_factor(), now2sec() - nows);
}
template <typename HMAP> static void bench_randomDistinct2(HMAP& hmap) {
auto map_name = find_hash(typeid(HMAP).name());
if (!map_name)
return;
printf(" %20s:", map_name);
#if X86_64 || __MAC__
constexpr size_t const n = 50000000;
#else
constexpr size_t const n = 50000000 / 2;
#endif
auto nows = now2sec();
MRNG rng(RND + 786512);
hmap.max_load_factor(max_lf);
[[maybe_unused]] int checksum;
{
// auto ts = now2sec();
checksum = 0;
size_t const max_rng = n / 20;
for (size_t i = 0; i < n; ++i) {
checksum += ++hmap[static_cast<int>(rng(max_rng))];
}
// printf(" 05%% distinct %.3f s loadf = %.2f, size = %d\n", now2sec() - ts, hmap.load_factor(),
// (int)hmap.size());
assert(RND != 123 || 549985352 == checksum);
}
{
hmap.clear();
// auto ts = now2sec();
checksum = 0;
size_t const max_rng = n / 4;
for (size_t i = 0; i < n; ++i) {
checksum += ++hmap[static_cast<int>(rng(max_rng))];
}
// printf(" 25%% distinct %.3f s loadf = %.2f, size = %d\n", now2sec() - ts, hmap.load_factor(),
// (int)hmap.size());
assert(RND != 123 || 149979034 == checksum);
}
{
hmap.clear();
// auto ts = now2sec();
size_t const max_rng = n / 2;
for (size_t i = 0; i < n; ++i) {
checksum += ++hmap[static_cast<int>(rng(max_rng))];
}
// printf(" 50%% distinct %.3f s loadf = %.2f, size = %d\n", now2sec() - ts, hmap.load_factor(),
// (int)hmap.size());
assert(RND != 123 || 249981806 == checksum);
}
{
hmap.clear();
// auto ts = now2sec();
checksum = 0;
for (size_t i = 0; i < n; ++i) {
checksum += ++hmap[static_cast<int>(rng())];
}
// printf(" 100%% distinct %.3f s loadf = %.2f, size = %d\n", now2sec() - ts, hmap.load_factor(),
// (int)hmap.size());
assert(RND != 123 || 50291811 == checksum);
}
//#endif
printf(" time %2.2f s\n", now2sec() - nows);
}
#define CODE_FOR_NUCLEOTIDE(nucleotide) (" \0 \1\3 \2"[nucleotide & 0x7])
template <typename HMAP> static size_t kcount(const std::vector<char>& poly, const std::string& oligo) {
HMAP hmap;
// hmap.max_load_factor(0.5);
uint64_t key = 0;
const uint64_t mask = ((uint64_t)1 << 2 * oligo.size()) - 1;
// For the first several nucleotides we only need to append them to key in
// preparation for the insertion of complete oligonucleotides to hmap.
for (size_t i = 0; i < oligo.size() - 1; ++i)
key = (key << 2 & mask) | (uint64_t)poly[i];
// Add all the complete oligonucleotides of oligo.size() to
// hmap and update the count for each oligonucleotide.
for (size_t i = oligo.size() - 1; i < poly.size(); ++i) {
key = (key << 2 & mask) | (uint64_t)poly[i];
++hmap[key];
}
// Generate the key for oligonucleotide.
key = 0;
for (size_t i = 0; i < oligo.size(); ++i) {
key = (key << 2) | (uint64_t)CODE_FOR_NUCLEOTIDE(oligo[i]);
}
if (oligo == "GGT")
printf(" (lf=%.2f) ", hmap.load_factor());
return hmap[key];
}
static int state = 42;
static inline int fasta_next() {
static constexpr int IM = 139968, IA = 3877, IC = 29573;
state = (state * IA + IC) % IM;
float p = (float)state * (1.0f / IM);
return (p >= 0.3029549426680f) + (p >= 0.5009432431601f) + (p >= 0.6984905497992f);
}
template <typename HMAP> static void bench_knucleotide() {
static constexpr size_t n = 25000000;
auto map_name = find_hash(typeid(HMAP).name());
if (!map_name)
return;
printf(" %20s:", map_name);
HMAP hmap;
state = RND;
for (size_t i = 0; i < n * 3; ++i)
(void)fasta_next();
std::vector<char> poly(n * 5);
for (size_t i = 0; i < poly.size(); ++i) {
poly[i] = (char)fasta_next();
}
auto nows = now2sec();
size_t ans = 0;
ans += kcount<HMAP>(poly, "GGTATTTTAATTTATAGT");
ans += kcount<HMAP>(poly, "GGTATTTTAATT");
ans += kcount<HMAP>(poly, "GGTATT");
ans += kcount<HMAP>(poly, "GGTA");
ans += kcount<HMAP>(poly, "GGT");
printf(" ans = %d time %2.2f s\n", (int)ans, now2sec() - nows);
}
class vec2 {
uint32_t m_xy;
public:
constexpr vec2(uint16_t x, uint16_t y) : m_xy{static_cast<uint32_t>(x) << 16U | y} {}
constexpr explicit vec2(uint32_t xy) : m_xy(xy) {}
[[nodiscard]] constexpr auto pack() const -> uint32_t { return m_xy; };
[[nodiscard]] constexpr auto add_x(uint16_t x) const -> vec2 {
return vec2{m_xy + (static_cast<uint32_t>(x) << 16U)};
}
[[nodiscard]] constexpr auto add_y(uint16_t y) const -> vec2 {
return vec2{(m_xy & 0xffff0000) | ((m_xy + y) & 0xffff)};
}