In other standard use cases, prefer "\n" because using std::endl in a loop for example can cause performance bottlenecks since it constantly forces the CPU to stop and flush data to the screen. Note that using the single character literal '\n' is slightly faster than the string literal "\n" because the compiler doesn't have to process a null-terminator (\0).
C++ and MATLAB Simulink tips for HWIL simulation software engineers
Thursday, January 23, 2025
C++ std::endl vs "\n"
I have a thread safe print function that uses lock_guard and std::cout and is called from different threads. When I replaced std::endl expressions with "\n", my program stopped printing to console. The main difference is that std::endl does two things: it inserts a newline character AND flushes the output buffer, while "\n" only inserts a newline character. In a multithreaded environment, without flushing, the output might stay in the buffer and not be visible immediately.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment