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

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

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
  • Проголосовать: не нравится

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

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

  • »
    »
    8 лет назад, скрыть # ^ |
     
    Проголосовать: нравится 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.

    • »
      »
      »
      8 лет назад, скрыть # ^ |
      ← 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.

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

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

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

Noam527 uses this.