-
-
Save qwercik/dce078fcf69babbc20bc76243416389b to your computer and use it in GitHub Desktop.
Performance test: std::endl vs "\n"
This file contains 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 <iostream> | |
#include <fstream> | |
#include <vector> | |
#include <chrono> | |
typedef void (*void_func_ptr_t)(void); | |
const int COUNT = 9999999; | |
struct Test | |
{ | |
std::string name; | |
void_func_ptr_t function; | |
}; | |
void withNewLine() | |
{ | |
std::ofstream file("output_endl.txt"); | |
for (int i = 0; i < COUNT; ++i) | |
file << "Message " << i + 1 << "\n"; | |
} | |
void withEndl() | |
{ | |
std::ofstream file("output_endl.txt"); | |
for (int i = 0; i < COUNT; ++i) | |
file << "Message " << i + 1 << std::endl; | |
} | |
int main() | |
{ | |
std::vector<Test> tests; | |
tests.push_back({ | |
"\\n", | |
withNewLine | |
}); | |
tests.push_back({ | |
"std::endl", | |
withEndl | |
}); | |
for (auto test : tests) | |
{ | |
auto startTime = std::chrono::high_resolution_clock::now(); | |
test.function(); | |
auto endTime = std::chrono::high_resolution_clock::now(); | |
std::cout << "Test " << test.name << "\n"; | |
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count() << " ms\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment