Skip to content

Instantly share code, notes, and snippets.

@ronen-fr
Created February 13, 2021 16:02
Show Gist options
  • Select an option

  • Save ronen-fr/ef44ea9386b0a5ae2121783873ea46c2 to your computer and use it in GitHub Desktop.

Select an option

Save ronen-fr/ef44ea9386b0a5ae2121783873ea46c2 to your computer and use it in GitHub Desktop.
fmtlib vs. strstream: (1) constructing text message from numbers and strings - google bench
float dt1 = 13.35f;
volatile int dt2 = 100;
volatile bool repair = true;
#include <sstream>
static void CondStrstr(benchmark::State& state) {
// Code before the loop is not measured
std::string x = "hello";
int c = 10;
for (auto _ : state) {
c *= -1;
std::stringstream oss;
oss << dt1 << " is " << x;
if (c > 0) {
oss << c << "errors";
} else {
oss << "ok";
}
if (repair) {
oss << repair << " fixed";
}
if (dt2 > 1) {
oss << dt2 << " dt2 ";
}
}
}
BENCHMARK(CondStrstr);
static void CondFmt(benchmark::State& state) {
// Code before the loop is not measured
std::string x = "hello";
int c = 10;
for (auto _ : state) {
c *= -1;
auto ret = fmt::format("{} is {}", dt1, x );
if (c > 0) {
ret += fmt::format(" {} errors", c);
} else {
ret += "ok";
}
if (repair) {
ret += fmt::format("{} fixed ", repair);
}
if (dt2 > 1) {
ret += fmt::format(" {} dt2", dt2);
}
}
}
BENCHMARK(CondFmt);
results:
Benchmark Time CPU Iterations
------------------------------------------------------------
CondStrstr 2636 ns 2622 ns 286515
CondStrstr 2614 ns 2598 ns 286515
CondStrstr 2607 ns 2595 ns 286515
CondStrstr 2649 ns 2627 ns 286515
CondStrstr 2709 ns 2689 ns 286515
CondStrstr 2680 ns 2668 ns 286515
CondStrstr 2655 ns 2630 ns 286515
CondStrstr 2709 ns 2686 ns 286515
CondStrstr 2655 ns 2642 ns 286515
CondStrstr 2616 ns 2579 ns 286515
CondStrstr_mean 2653 ns 2634 ns 10
CondStrstr_median 2652 ns 2629 ns 10
CondStrstr_stddev 37.0 ns 38.0 ns 10
CondFmt 770 ns 767 ns 891145
CondFmt 756 ns 753 ns 891145
CondFmt 779 ns 769 ns 891145
CondFmt 749 ns 746 ns 891145
CondFmt 749 ns 742 ns 891145
CondFmt 767 ns 763 ns 891145
CondFmt 757 ns 754 ns 891145
CondFmt 758 ns 755 ns 891145
CondFmt 739 ns 736 ns 891145
CondFmt 710 ns 703 ns 891145
CondFmt_mean 754 ns 749 ns 10
CondFmt_median 756 ns 753 ns 10
CondFmt_stddev 19.2 ns 19.2 ns 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment