#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <ctime>
int main(int argc, char* argv[])
{
std::clock_t start;
double duration;
std::cout << "Starting std::cout test." << std::endl;
start = std::clock();
for (int i = 0; i < 1000; i++)
{
std::cout << "Hello, World! (" << i << ")" << std::endl;
}
duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
std::cout << "Ending std::cout test." << std::endl;
std::cout << "Time taken: " << duration << std::endl;
std::system("pause");
std::cout << "Starting std::printf test." << std::endl;
start = std::clock();
for (int i = 0; i < 1000; i++)
{
std::printf("Hello, World! (%i)\n", i);
std::fflush(stdout);
}
duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
std::cout << "Ending std::printf test." << std::endl;
std::cout << "Time taken: " << duration << std::endl;
system("pause");
return 0;
}
Now, here are the times for the first five runs:
- std::cout test: 1.125 s ; printf test: 0.195 s
- std::cout test: 1.154 s ; printf test: 0.230 s
- std::cout test: 1.142 s ; printf test: 0.216 s
- std::cout test: 1.322 s ; printf test: 0.221 s
- std::cout test: 1.108 s ; printf test: 0.232 s
As you can see, using printf
and then fflush
ing takes about 5 times less time than using std::cout
.
Although I did expect using std::cout
's <<
operator to be perhaps a little slower (almost minimal) , I wasn't prepared for this huge difference. Am I making a fair test? If so, then what makes the first test so much slower than the second one, if they essentially do the exact same thing?
std::endl
in every iteration is a bad idea. Use'\n'
. They're not the same thing. – Rota**what makes** the first test so much slower than the second one...
i.e why exactly is the printf faster? – Aleececout
faster thenprintf
, but only if I set-std=c++0x
. – Cinnamonstd::cout << "Hello, World! (" << i << ")" << std::endl;
is 4 function calls, whileprintf
is only one. Try doingprintf
5 times, like withcout
and see what happens. Then you'll realize how much of the performance fail is due to function calls, and how much due the library itself. – Pudgystd::cout.sync_with_stdio(false);
– Triadelphousstdout
for eachprintf
. Without thestd::fflush(stdout);
theprintf
loop executes much faster. While it is idiomatic to<< std::endl
, it is not idiomatic tofflush(stdout)
. Unsuspecting C++ programmers are likely to usecout
much less inefficiently thenstdout
– Babylon