Reputation: 9
I'm working on a code that performs the Josephus's permutation. I noticed that when I use redirection, its faster than when I use cout
or printf
. Please I would like to know from anyone having experience, which one is usually faster as i am mostly concerned with code performance and timing.
Thanks.
Upvotes: 1
Views: 329
Reputation: 18902
It depends on your OS an your platform's implementation of the C and C++ I/O libraries (... and cpu load, services, processes, RAM...).
On Windows, writing to the console is a huge bottleneck. Usually it's faster on Linux / MacOS (e.g. Performance difference of iostream console output between Windows and OSX?).
Writing to an ofstream
directly could increase performance if it uses a different buffering scheme compared to cout
(and this is often the case).
Anyway with streams
you can speed up the printing significantly using '\n'
instead of std::endl
:
std::cout << "Test line\n";
is faster than:
std::cout << "Test line" << std::endl;
since the latter is equivalent to:
std::cout << "Test line\n" << std::flush;
(see C++: "std::endl" vs "\n" for further details).
Some references:
Upvotes: 1