Skip to content

Instantly share code, notes, and snippets.

@virtuosonic
Created August 23, 2023 22:56
Show Gist options
  • Save virtuosonic/22fad3b383033e9c06a11eda681f1728 to your computer and use it in GitHub Desktop.
Save virtuosonic/22fad3b383033e9c06a11eda681f1728 to your computer and use it in GitHub Desktop.
/**********************\
Name: format_test.cpp
Author: Gabriel Espinoza <[email protected]>
License: MIT
Desc: string concatenation and output test benchmark
*/
//!!!! C++ 2020 required
#include <iostream>
#include <chrono>
#include <functional>
#include <string_view>
#include <format>
#include <strstream>
using namespace std;
using namespace std::chrono;
auto run1Mtimes(string_view s,function<void()> f)
{
auto start = system_clock::now();
for(int i = 0 ; i < 1'000; ++i)
{
f();
}
auto d = duration_cast<microseconds>(system_clock::now() - start).count();
return format("function {} took {} us to run\n",s,d);
}
int main()
{
ios::sync_with_stdio(false);
string_view s {"output to cout"};
double d = 1.6;
int i = 123;
vector<string> v;
v.push_back(run1Mtimes("format",[&](){ cout << format("{} {} {}\n",s,d,i);}));
v.push_back(run1Mtimes("ostringstream",[&](){
ostringstream os;
os << s << " " << d << " " << i << endl;
cout << os.str();
}));
v.push_back(run1Mtimes("+",[&](){ cout << string() + s.data() + " " + to_string(d) + " " + to_string(i) +"\n";}));
v.push_back(run1Mtimes("+=",[&](){
string str;
str += s.data();
str += " ";
str += to_string(d);
str += " ";
str += to_string(i);
str += "\n";
cout << str;
}));
v.push_back(run1Mtimes("printf",[&](){
printf("%s %f %i\n",s.data(),d,i);
}));
v.push_back(run1Mtimes("cout",[&](){ cout << s << " " << d << " " << i << endl;}));
ranges::copy(v,ostream_iterator<string>(cerr,"\n"));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment