1

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.

Python_user
  • 1,378
  • 3
  • 12
  • 25
  • Define "faster", the delay is probably because **you're printing stuff to the console window**, if you don't need the info don't print anything or dump it to `/dev/nul` / `NUL`. That said I'm sure `std::ios_base::sync_with_stdio(false)` will help if you aren't already using it (and you don't need to mix `printf` with `cout`). – user657267 Jan 28 '15 at 09:15

1 Answers1

1

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:

Community
  • 1
  • 1
manlio
  • 18,345
  • 14
  • 76
  • 126
  • @peter, thanks a lot, i was able to make if faster using \n, i also see the difference now on linux and macOS. cuz i tried it on different platforms, although i mostly work with windows. – user3081810 Jan 29 '15 at 14:58