Ticket #782: benchmark-encode_length.cc

File benchmark-encode_length.cc, 1.6 KB (added by German M. Bravo, 6 years ago)

Benchmarking code

Line 
1/*
2c++ -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
9template<class T>
10std::string
11encode_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}
31static void BM_EncodeLength_Original(benchmark::State& state) {
32 unsigned long long x = std::numeric_limits<unsigned long long>::max() - 10;
33 while (state.KeepRunning()) {
34 for (auto i = x; i != 0; i >>= 1) {
35 encode_length_original(i);
36 }
37 }
38}
39BENCHMARK(BM_EncodeLength_Original);
40
41
42template<class T>
43std::string
44encode_length_optimized(T len)
45{
46 char result[12];
47 char* end = result;
48 unsigned char b = static_cast<unsigned char>(len);
49 if (len >= 255) {
50 b = '\xff';
51 len -= 255;
52 do {
53 *end++ = b;
54 b = static_cast<unsigned char>(len & 0x7f);
55 len >>= 7;
56 } while (len);
57 b |= static_cast<unsigned char>(0x80);
58 }
59 *end++ = b;
60 return std::string(result, end);
61}
62static void BM_EncodeLength_Optimized(benchmark::State& state) {
63 unsigned long long x = std::numeric_limits<unsigned long long>::max() - 10;
64 while (state.KeepRunning()) {
65 for (auto i = x; i != 0; i >>= 1) {
66 encode_length_optimized(i);
67 }
68 }
69}
70BENCHMARK(BM_EncodeLength_Optimized);
71
72
73BENCHMARK_MAIN();