Skip to content

Instantly share code, notes, and snippets.

@LucianoPAlmeida
Last active January 4, 2023 00:25
Show Gist options
  • Save LucianoPAlmeida/a80849b54ccd88f5fd748d29238c024f to your computer and use it in GitHub Desktop.
Save LucianoPAlmeida/a80849b54ccd88f5fd748d29238c024f to your computer and use it in GitHub Desktop.
class A {
std::vector<std::string> _values;
public:
void addValue(const std::string &val) {
// some logic
_values.emplace_back(val);
}
void addValue(std::string &&val) { // r-value ref overload
// some logic
_values.emplace_back(std::move(val)); // We know that is a r-value
}
};
class B {
std::vector<std::string> _values;
public:
void addValue(const std::string &val) {
// some logic
_values.emplace_back(val);
}
};
std::string f() {
return std::string("a long enough string that will better show our results in our awesome benchmark");
}
static void AddValueCopy(benchmark::State& state) {
// Code inside this loop is measured repeatedly
for (auto _ : state) {
B b;
for(int i = 0; i < 10; ++i) {
auto v = f();
b.addValue(v);
}
benchmark::DoNotOptimize(b);
}
}
// Register the function as a benchmark
BENCHMARK(AddValueCopy);
static void AddValueMove(benchmark::State& state) {
// Code before the loop is not measured
for (auto _ : state) {
A a;
for(int i = 0; i < 10; ++i) {
a.addValue(f());
}
benchmark::DoNotOptimize(a);
}
}
BENCHMARK(AddValueMove);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment