Skip to content

Instantly share code, notes, and snippets.

@qwercik
Last active August 1, 2017 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qwercik/dce078fcf69babbc20bc76243416389b to your computer and use it in GitHub Desktop.
Save qwercik/dce078fcf69babbc20bc76243416389b to your computer and use it in GitHub Desktop.
Performance test: std::endl vs "\n"
#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