Created
July 31, 2017 19:48
-
-
Save ranisalt/ce573f8d0e17ed4e4ed4107df2b3f09c to your computer and use it in GitHub Desktop.
bool to str benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <chrono> | |
#include <iostream> | |
#include <sstream> | |
using namespace std::chrono; | |
constexpr auto SAMPLES = 100'000u; | |
auto curr_time() | |
{ | |
return high_resolution_clock::now(); | |
} | |
int main() | |
{ | |
{ | |
uint64_t sum = 0; | |
for (auto j = 0u; j < SAMPLES; ++j) { | |
std::stringstream ss; | |
bool r = rand() & 1; | |
ss << std::boolalpha; | |
auto start = curr_time(); | |
ss << r; | |
auto end = curr_time(); | |
sum += duration_cast<nanoseconds>(end - start).count(); | |
} | |
std::cout << "Stream took " << sum / SAMPLES << "ns (" << SAMPLES << " samples)\n"; | |
} | |
{ | |
uint64_t sum = 0; | |
for (auto j = 0u; j < SAMPLES; ++j) { | |
bool r = rand() & 1; | |
auto start = curr_time(); | |
snprintf(nullptr, 0, "%s", r ? "true" : "false"); | |
auto end = curr_time(); | |
sum += duration_cast<nanoseconds>(end - start).count(); | |
} | |
std::cout << "Ternary took " << sum / SAMPLES << "ns (" << SAMPLES << " samples)\n"; | |
} | |
{ | |
uint64_t sum = 0; | |
for (auto j = 0u; j < SAMPLES; ++j) { | |
bool r = rand() & 1; | |
auto start = curr_time(); | |
snprintf(nullptr, 0, "%s", "false\0true" + (+r * 6)); | |
auto end = curr_time(); | |
sum += duration_cast<nanoseconds>(end - start).count(); | |
} | |
std::cout << "Offset took " << sum / SAMPLES << "ns (" << SAMPLES << " samples)\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment