aboutsummaryrefslogtreecommitdiff
path: root/src/node/minisketchwrapper.cpp
blob: 572df63463abb25d09d888922b3a4f56189cc46e (plain)
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
// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <node/minisketchwrapper.h>

#include <logging.h>
#include <util/time.h>

#include <minisketch.h>

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <utility>
#include <vector>

namespace {

static constexpr uint32_t BITS = 32;

uint32_t FindBestImplementation()
{
    std::optional<std::pair<int64_t, uint32_t>> best;

    uint32_t max_impl = Minisketch::MaxImplementation();
    for (uint32_t impl = 0; impl <= max_impl; ++impl) {
        std::vector<int64_t> benches;
        uint64_t offset = 0;
        /* Run a little benchmark with capacity 32, adding 184 entries, and decoding 11 of them once. */
        for (int b = 0; b < 11; ++b) {
            if (!Minisketch::ImplementationSupported(BITS, impl)) break;
            Minisketch sketch(BITS, impl, 32);
            auto start = GetTimeMicros();
            for (uint64_t e = 0; e < 100; ++e) {
                sketch.Add(e*1337 + b*13337 + offset);
            }
            for (uint64_t e = 0; e < 84; ++e) {
                sketch.Add(e*1337 + b*13337 + offset);
            }
            offset += (*sketch.Decode(32))[0];
            auto stop = GetTimeMicros();
            benches.push_back(stop - start);
        }
        /* Remember which implementation has the best median benchmark time. */
        if (!benches.empty()) {
            std::sort(benches.begin(), benches.end());
            if (!best || best->first > benches[5]) {
                best = std::make_pair(benches[5], impl);
            }
        }
    }
    assert(best.has_value());
    LogPrintf("Using Minisketch implementation number %i\n", best->second);
    return best->second;
}

uint32_t Minisketch32Implementation()
{
    // Fast compute-once idiom.
    static uint32_t best = FindBestImplementation();
    return best;
}

} // namespace


Minisketch MakeMinisketch32(size_t capacity)
{
    return Minisketch(BITS, Minisketch32Implementation(), capacity);
}

Minisketch MakeMinisketch32FP(size_t max_elements, uint32_t fpbits)
{
    return Minisketch::CreateFP(BITS, Minisketch32Implementation(), max_elements, fpbits);
}