Skip to content

Instantly share code, notes, and snippets.

@kevinkreiser
Created June 22, 2021 02:05
Show Gist options
  • Save kevinkreiser/1a7c9a7cc803a51e79f76a5e0e53730f to your computer and use it in GitHub Desktop.
Save kevinkreiser/1a7c9a7cc803a51e79f76a5e0e53730f to your computer and use it in GitHub Desktop.
#include <sstream>
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
// To test performance you can compile with different preprocessor defines:
// g++ -std=c++11 -O2 -D USE_PRINTF string_format.cpp -o using_printf
// g++ -std=c++11 -O2 -D USE_IOSTREAM string_format.cpp -o using_iostream
// g++ -std=c++11 -O2 -D USE_STRING string_format.cpp -o using_string
// Then you can simply time multiple runs of each program:
// time using_printf
// time using_iostream
// time using_string
//On my machine the results are as follows:
//printf: 2.5 seconds
//ostream: 6.9 seconds
//string: 1.6 seconds
int main() {
std::vector<const char*> types = { "c", "ms", "h", "g", "s"};
std::string prefix = "foo";
std::vector<std::string> keys = { "bar", "baz", "qux", "quux", "corge", "gorge" };
// testing 3 ways to do string formatting for statsd like messages
std::string buffer(256, '\0');
bool needs_dot = true;
for(int value =0; value < 10000000; ++value) {
float freq = (value % 11) / 10.f;
#ifdef USE_PRINTF
if(freq < 1.f) {
std::snprintf(&buffer.front(),
buffer.size(),
"%s%s%s:%d|%s|@%.2f",
prefix.c_str(),
needs_dot ? "." : "",
keys[value % keys.size()].c_str(),
value,
types[value % types.size()],
freq);
}
else {
std::snprintf(&buffer.front(),
buffer.size(),
"%s%s%s:%d|%s",
prefix.c_str(),
needs_dot ? "." : "",
keys[value % keys.size()].c_str(),
value,
types[value % types.size()]);
}
#endif
#ifdef USE_IOSTREAM
std::ostringstream ss;
ss.precision(2);
ss << prefix << (needs_dot ? "." : "")<<
keys[value % keys.size()].c_str()<<':'<<
value<<'|'<<
types[value % types.size()];
if(freq < 1.f)
ss <<"|@"<< std::fixed << freq;
auto str = ss.str();
#endif
#ifdef USE_STRING
buffer.clear();
buffer.append(prefix);
if(needs_dot)
buffer.push_back('.');
buffer.append(keys[value % keys.size()]);
buffer.push_back(':');
buffer.append(std::to_string(value));
buffer.push_back('|');
buffer.append(types[value % types.size()]);
if(freq < 1.f) {
buffer.append("|@0.");
buffer.append(std::to_string(static_cast<int>(freq * 100)));
}
#endif
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment