As easy as my title and the rules of the C++ core guidelines sound, getting more performance out of the iostreams is no no-brainer.
Okay, let’s step back. Although I did a lot of tests, my numbers in this post are more controversial than I thought. Please let me know if you have any ideas, improvements, or clarifications, and I will add them to this post.
Here are the two performance-related rules from the guidelines to Iostreams.
- SL.io.10: Unless you use
printf-family functions call
- SL.io.50: Avoid
I assume you don’t know std::ios_base::sync_with_stdio?
Per default, operations on the C++ streams are synchronized with the C streams. This synchronization happens after each in- or output operation.
- C++ Streams: std::cin, std::cout, std::cerr, std::clog, std::wcin, std::wcout, std::wcerr, and std::wclog.
- C Streams: stdin, stdout, and stderr.
This allows it to mix C++ and C in- or output operations because operations on the C++ streams go unbuffered to the C streams. What is also important to note from the concurrency perspective: synchronized C++ streams are thread-safe. All threads can write to the C++ streams without any need for synchronization. The effect may be an interleaving of characters but not a data race.
When you set the std::ios_base::sync_with_stdio(false), the synchronization between C++ streams and C streams will not happen because the C++ stream may put its output into a buffer. Because of the buffering, the in- and output operation may become faster. You must invoke std::ios_base::sync_with_stdio(false) before any in- or output operation. If not, the behavior is implementation-defined.
I assume you noticed that I wrote quite often, maybe. That is for a reason.
Interleaving of C++ Streams and C Streams
First, I want to know what would happen when I execute the following program with various compilers.
I add a few pieces of information to get a better picture of my various compiler.
It seems that only the output on GCC is not synchronized. This observation does not hold for clang or cl.exe on Windows. A small performance test confirmed my first impression.
Performance with and without Synchronisation
Let me write a small program with and without synchronization to the console. Doing it without synchronization should be faster.
The program is relatively easy to explain. I open a file (line 1), read its entire content (line 2) into a string, and write its iterations-times to the console (line 3). This is done in the function writeToConsole(fileContent).
iterations are in my concrete case 10. In the end, I display the average time of the output operations (line 4).
The non-synchronized version of the program is quite similar to the synchronized version. Only the main function changed a bit.
I just added line (1) to the main program. Now, I hope for performance improvement.
I did my performance test with a small program and a bigger text file (600.000 characters). The bigger file gave me no new insight; therefore, I skipped it.
The results puzzled me because of Windows.
- With GCC, I had a performance improvement of about 70% in the non-synchronized variant.
- Neither Clang nor cl.exe showed any performance improvement. It seems that the non-synchronized in- and output operations are synchronized. My numbers proved my observation from the program syncWithStdio.cpp.
- Only for the record. Did you notice how slow the console on windows is?
Of course, I’m guilty. I almost always break the following rule.
Why should you avoid std::endl? Or, to say it differently: What is the difference between the manipulator std::endl and ‘\n’.
- std::endl: writes a new line and flushes the output buffer.
- ‘\n’: writes a new line.
Flushing the buffer is expensive and should, therefore, be avoided. If necessary, the buffer is automatically flushed. Honestly, I was curious to see the numbers. To make it extremely worse, here is my program, which puts a linebreak (line 3) after each character.
In the first case, I did it with std::endl (line 2); in the second case, I did it with ‘\n‘ (line 3). The program is quite similar to the previous one. The big difference is that I made 500 iterations (line 3). Why? I was astonished by the variations in the numbers. With a few iterations, I could not notice any difference. Sometimes, std::endl was two times faster than ‘\n’; sometimes, std::endl was four times slower. I got similar behavior with cl.exe or with GCC. I also did it with another GCC or cl.exe compiler. Honestly, this was not what I expected. When I did it with 500 iterations, I got the expected winner. ‘\n‘ seems to be 10% – 20% faster than std::endl. Once more, only 10% – 20% faster.
My Small Conclusion
I want to draw a small conclusion from my performance test.
- std::ios_base::sync_with_stdio(false) can make a big difference on your platform, but you lose your thread-safety guarantee.
- std::endl is not as bad as its reputation. I will not change my habit.
Only one rule exists for the sections regex, chrono, and the C standard library. You see, I have to improvise in my next post.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, and Marco Parri Empoli.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,