4

Possible Duplicate:
C++: “std::endl” vs “\n”

I have a simple program I tested and I realise that endl wreaks havoc on my program. Using endl, my program ran in 100+ ms while working with '\n', the time dropped to ~50ms. Can anyone tell why is there such a difference?

P.S. I did read other posts that somehow explained what each of them are doing, but does std::flush really take so much time?
Or could there be another possible explanation?

Community
  • 1
  • 1
Mihai Bujanca
  • 4,089
  • 10
  • 43
  • 84

2 Answers2

6

std::endl writes a newline, and flushes the buffer. As you have discovered, the flush can be a rather expensive operation.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • It's quite strange to me that this thing can double the execution time. Thank you – Mihai Bujanca Nov 24 '12 at 21:47
  • @BujancaMihai: If there's doubt in your mind, compare the timings of: (1) `endl`; (2) `\n`; (3) `\n` followed by `flush`. – NPE Nov 24 '12 at 21:50
  • No doubt, I already tried and the difference is obvious. I was aware that the `flushing` occurs but not that it is such an expensive operation. Many thanks – Mihai Bujanca Nov 24 '12 at 21:51
  • @BujancaMihai: maybe the cost of the flush depends on how much things you have to flush, so it's hard to predict how expensive the operation will be. – effeffe Nov 25 '12 at 00:53
2

endl has extra expensive flush() operation

27.7.3.8 Standard basic_ostream manipulators [ostream.manip]

namespace std {
template <class charT, class traits>
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
}
1 Effects: Calls os.put(os.widen(’\n’)), then os.flush().
2 Returns: os.
billz
  • 44,644
  • 9
  • 83
  • 100