1 | /*
|
---|
2 | c++ -std=c++1z -pedantic -Wall -Wextra -O3 -lbenchmark -lbenchmark_main -I. -I./src -I../src -I.. -o benchmark-encode_length ./benchmark-encode_length.cc && ./benchmark-encode_length
|
---|
3 | */
|
---|
4 | #include <limits>
|
---|
5 |
|
---|
6 | #include "benchmark/benchmark.h"
|
---|
7 |
|
---|
8 |
|
---|
9 | template<class T>
|
---|
10 | std::string
|
---|
11 | encode_length_original(T len)
|
---|
12 | {
|
---|
13 | std::string result;
|
---|
14 | if (len < 255) {
|
---|
15 | result += static_cast<unsigned char>(len);
|
---|
16 | } else {
|
---|
17 | result += '\xff';
|
---|
18 | len -= 255;
|
---|
19 | while (true) {
|
---|
20 | unsigned char b = static_cast<unsigned char>(len & 0x7f);
|
---|
21 | len >>= 7;
|
---|
22 | if (!len) {
|
---|
23 | result += char(b | static_cast<unsigned char>(0x80));
|
---|
24 | break;
|
---|
25 | }
|
---|
26 | result += b;
|
---|
27 | }
|
---|
28 | }
|
---|
29 | return result;
|
---|
30 | }
|
---|
31 |
|
---|
32 | const unsigned long long x = 0xfff;
|
---|
33 | //const unsigned long long x = std::numeric_limits<unsigned long>::max() - 10;
|
---|
34 | static void BM_EncodeLength_Original(benchmark::State& state) {
|
---|
35 | for (auto _ : state) {
|
---|
36 | std::string s;
|
---|
37 | for (auto i = x; i != 0; i >>= 1) {
|
---|
38 | s += encode_length_original(i);
|
---|
39 | }
|
---|
40 | }
|
---|
41 | }
|
---|
42 | BENCHMARK(BM_EncodeLength_Original);
|
---|
43 |
|
---|
44 |
|
---|
45 | template<class T>
|
---|
46 | std::string
|
---|
47 | encode_length_optimized(T len)
|
---|
48 | {
|
---|
49 | char result[12];
|
---|
50 | char* end = result;
|
---|
51 | unsigned char b = static_cast<unsigned char>(len);
|
---|
52 | if (len >= 255) {
|
---|
53 | b = '\xff';
|
---|
54 | len -= 255;
|
---|
55 | do {
|
---|
56 | *end++ = b;
|
---|
57 | b = static_cast<unsigned char>(len & 0x7f);
|
---|
58 | len >>= 7;
|
---|
59 | } while (len);
|
---|
60 | b |= static_cast<unsigned char>(0x80);
|
---|
61 | }
|
---|
62 | *end++ = b;
|
---|
63 | return std::string(result, end);
|
---|
64 | }
|
---|
65 | static void BM_EncodeLength_Optimized(benchmark::State& state) {
|
---|
66 | for (auto _ : state) {
|
---|
67 | std::string s;
|
---|
68 | for (auto i = x; i != 0; i >>= 1) {
|
---|
69 | s += encode_length_optimized(i);
|
---|
70 | }
|
---|
71 | }
|
---|
72 | }
|
---|
73 | BENCHMARK(BM_EncodeLength_Optimized);
|
---|
74 |
|
---|
75 |
|
---|
76 | //BENCHMARK_MAIN();
|
---|