Skip to content

Instantly share code, notes, and snippets.

@j178
Last active April 11, 2023 11:36
Show Gist options
  • Save j178/a026911f3d7aefbf095e0f8ec32c6c53 to your computer and use it in GitHub Desktop.
Save j178/a026911f3d7aefbf095e0f8ec32c6c53 to your computer and use it in GitHub Desktop.
Compile with `g++ -std=c++11 -O2 bench.cpp -o bench`
#include <iostream>
#include <chrono>
#include <sstream>
using namespace std;
using namespace chrono;
// Method 1: Using a conditional operator
string bool_to_string_conditional(bool b) {
return b ? "true" : "false";
}
// Method 2: Using a stringstream
string bool_to_string_stringstream(bool b) {
stringstream ss;
ss << boolalpha << b;
return ss.str();
}
// Method 3: Using to_string function
string bool_to_string_to_string(bool b) {
return to_string(b);
}
// Method 4: Using computed string indices
string bool_to_string_computed_index(bool b) {
return string(&"false\0\0\0true"[b<<3], 5-b);
}
int main() {
// Evaluate conversion time for 10000000 iterations
const int iterations = 10000000;
bool b = true;
string result;
auto start = high_resolution_clock::now();
// Method 1: Using a conditional operator
for (int i = 0; i < iterations; i++) {
b = !b;
result = bool_to_string_conditional(b);
}
auto end = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(end - start);
cout << "Method 1: Using conditional operator -> " << duration.count() << " microseconds." << endl;
// Method 2: Using a stringstream
start = high_resolution_clock::now();
for (int i = 0; i < iterations; i++) {
b = !b;
result = bool_to_string_stringstream(b);
}
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
cout << "Method 2: Using stringstream -> " << duration.count() << " microseconds." << endl;
// Method 3: Using to_string function
start = high_resolution_clock::now();
for (int i = 0; i < iterations; i++) {
b = !b;
result = bool_to_string_to_string(b);
}
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
cout << "Method 3: Using to_string function -> " << duration.count() << " microseconds." << endl;
// Method 4: Using computed string indices
start = high_resolution_clock::now();
for (int i = 0; i < iterations; i++) {
b = !b;
result = bool_to_string_computed_index(b);
}
end = high_resolution_clock::now();
duration = duration_cast<microseconds>(end - start);
cout << "Method 4: Using computed index -> " << duration.count() << " microseconds." << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment