Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between endl and '\n' [duplicate]

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?

like image 298
Mihai Bujanca Avatar asked Feb 18 '23 09:02

Mihai Bujanca


2 Answers

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

like image 197
NPE Avatar answered Feb 27 '23 15:02

NPE


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.
like image 40
billz Avatar answered Feb 27 '23 15:02

billz