Блог пользователя leafvillageninja

Автор leafvillageninja, история, 5 лет назад, По-английски

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.

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

»
5 лет назад, # |
  Проголосовать: нравится +40 Проголосовать: не нравится

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

  • »
    »
    5 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    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.

    • »
      »
      »
      5 лет назад, # ^ |
      Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

      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.

    • »
      »
      »
      5 лет назад, # ^ |
      Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

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

»
5 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Noam527 uses this.

  • »
    »
    5 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Thanks, I'll use this too :-)

  • »
    »
    5 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    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.