merkle_root.cpp raw
1 // Copyright (c) 2016-present The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #include <bench/bench.h>
6 #include <consensus/merkle.h>
7 #include <random.h>
8 #include <uint256.h>
9 #include <util/check.h>
10
11 #include <initializer_list>
12 #include <utility>
13 #include <vector>
14
15 static void MerkleRoot(benchmark::Bench& bench)
16 {
17 FastRandomContext rng{/*fDeterministic=*/true};
18
19 std::vector<uint256> hashes{};
20 hashes.resize(9001);
21 for (auto& item : hashes) {
22 item = rng.rand256();
23 }
24
25 constexpr uint256 expected_root{"d8d4dfd014a533bc3941b8663fa6e7f3a8707af124f713164d75b0c3179ecb08"};
26 for (bool mutate : {false, true}) {
27 bench.name(mutate ? "MerkleRootWithMutation" : "MerkleRoot").batch(hashes.size()).unit("leaf").run([&] {
28 std::vector<uint256> leaves;
29 leaves.reserve((hashes.size() + 1) & ~1ULL); // capacity rounded up to even
30 for (const auto& hash : hashes) {
31 leaves.push_back(hash);
32 }
33
34 bool mutated{false};
35 const uint256 root{ComputeMerkleRoot(std::move(leaves), mutate ? &mutated : nullptr)};
36 assert(root == expected_root);
37 });
38 }
39 }
40
41 BENCHMARK(MerkleRoot);
42