leafvillageninja's blog

By leafvillageninja, history, 6 years ago, In English

Isn't it a good idea to use a macro which replaces all the instances of endl with "\n" in all of my C++ programs to speed-up my code because doing so will stop unnecessary flushing of stdout?

Asking this because I have never seen anyone using such a macro.

Of course, in certain problems like the interactive ones, where I have to flush stdout, I will have to write fflush(stdout) separately.

  • Vote: I like it
  • +8
  • Vote: I do not like it

»
6 years ago, # |
  Vote: I like it +40 Vote: I do not like it

What about just using "\n" where you need it?

  • »
    »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Of course, but I'm habitual of writing endl to end lines. "Is there any advantage of using "\n" instead of using a macro?" — this is what I intended to ask. I'm sorry that my original post couldn't clarify my intention.

    • »
      »
      »
      6 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      endl flushes output and forces data being written to disk. And this can significantly slow your program if you are doing this a lot.

      Go to customtest and compare running time of this

      #include <iostream>
      
      using namespace std;
      
      int main() {
          for (int i = 0; i < 1000000; i++) {
              cout << i << endl;
          }
      }
      

      and this

      #include <iostream>
      
      using namespace std;
      
      int main() {
          for (int i = 0; i < 1000000; i++) {
              cout << i << "\n";
          }
      }
      

      UPD: I've misread the question, sorry for pointing out things that are already clear.

    • »
      »
      »
      6 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      if you use endl in interactive problems define may bite you.

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Noam527 uses this.

  • »
    »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks, I'll use this too :-)

  • »
    »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I started using this once I heard '\n' is quicker than endl, and I was used to write endl, but I had to write this template enough times that now I don't mind writing either of them, but now I'm used to this template so I'm still using endl because I keep forgetting to remove the #define, and if it's there then I should use it anyway.

    It's all pointless.