/ src / bench / parse_hex.cpp
parse_hex.cpp
 1  // Copyright (c) 2024-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 <random.h>
 7  #include <util/strencodings.h>
 8  
 9  #include <cassert>
10  #include <cstddef>
11  #include <optional>
12  #include <vector>
13  
14  std::string generateHexString(size_t length) {
15      const auto hex_digits = "0123456789ABCDEF";
16      FastRandomContext rng(/*fDeterministic=*/true);
17  
18      std::string data;
19      while (data.size() < length) {
20          auto digit = hex_digits[rng.randbits(4)];
21          data.push_back(digit);
22      }
23      return data;
24  }
25  
26  static void HexParse(benchmark::Bench& bench)
27  {
28      auto data = generateHexString(130); // Generates 678B0EDA0A1FD30904D5A65E3568DB82DB2D918B0AD8DEA18A63FECCB877D07CAD1495C7157584D877420EF38B8DA473A6348B4F51811AC13C786B962BEE5668F9 by default
29  
30      bench.batch(data.size()).unit("base16").run([&] {
31          auto result = TryParseHex(data);
32          assert(result != std::nullopt); // make sure we're measuring the successful case
33          ankerl::nanobench::doNotOptimizeAway(result);
34      });
35  }
36  
37  BENCHMARK(HexParse, benchmark::PriorityLevel::HIGH);