Created
April 30, 2021 19:49
-
-
Save dannas/d75462235ce0a862cffd4225165726e9 to your computer and use it in GitHub Desktop.
Benchmark ways of passing strings to functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define RUN_ME /* | |
g++ -Wall -std=c++17 $(pkg-config benchmark --cflags) -O2 $0 -o $(basename $0 .cpp) $(pkg-config benchmark --libs) -lpthread | |
./$(basename $0 .cpp) | |
exit 0 | |
*/ | |
// -------------------------------------------------- | |
// Benchmark Time CPU Iterations | |
// -------------------------------------------------- | |
// BM_r1 52 ns 52 ns 12272152 | |
// BM_r2 30 ns 30 ns 23541703 | |
// BM_r3 36 ns 36 ns 19523162 | |
// BM_r4 27 ns 27 ns 25579177 | |
#include <string> | |
#include <string_view> | |
#include <algorithm> | |
#include <benchmark/benchmark.h> | |
#define TEXT "abcdefghijklmnopqrstuvwxyz" | |
using std::string; | |
using std::string_view; | |
using std::reverse; | |
static string reverse_string1(const string &str) { | |
string copy = str; | |
reverse(begin(copy), end(copy)); | |
return copy; | |
} | |
static string reverse_string2(string str) { | |
reverse(begin(str), end(str)); | |
return str; | |
} | |
static string reverse_string3(string_view str) { | |
string copy = string(str); | |
reverse(begin(copy), end(copy)); | |
return copy; | |
} | |
static string reverse_string4(string_view str) { | |
return string(rbegin(str), rend(str)); | |
} | |
static void BM_r1(benchmark::State& state) { | |
for (auto _ : state) { | |
benchmark::DoNotOptimize(reverse_string1(TEXT)); | |
} | |
} | |
BENCHMARK(BM_r1); | |
static void BM_r2(benchmark::State& state) { | |
for (auto _ : state) { | |
benchmark::DoNotOptimize(reverse_string2(TEXT)); | |
} | |
} | |
BENCHMARK(BM_r2); | |
static void BM_r3(benchmark::State& state) { | |
for (auto _ : state) { | |
benchmark::DoNotOptimize(reverse_string3(TEXT)); | |
} | |
} | |
BENCHMARK(BM_r3); | |
static void BM_r4(benchmark::State& state) { | |
for (auto _ : state) { | |
benchmark::DoNotOptimize(reverse_string4(TEXT)); | |
} | |
} | |
BENCHMARK(BM_r4); | |
BENCHMARK_MAIN(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment