Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does std::ios_base::sync_with_stdio impact stream buffering?

Tags:

c++

iostream

Both this answer on Stack Overflow and cppreference.com suggest turning off stream synchronization to improve performance, arguing that stream synchronization would disable buffering.

Now this is what I do not understand. Why can't synchronized streams simply share buffers? I imagined that if the streams are synchronized, std::fputc(stdout, c); could simply be implemented in terms of std::cout << c; or the other way round (or using a common primitive). So whenever C I/O is mixed with C++ I/O, synchronized streams would even have an advantage over non-synchronized ones! Fewer buffers, fewer cache misses.

The current C++ standard draft seems to be with me here. In the footnote where sync_with_stdio() is specified, it says "In practical terms, synchronization usually means that a standard iostream object and a standard stdio object share a buffer." Is it possible that the links I posted above merely document some imperfect implementations and their performance implications?

Also, because I do not see any theoretical disadvantage of non-synchronized streams, I am wondering why these exist in the first place.

like image 524
purefanatic Avatar asked Feb 15 '26 22:02

purefanatic


1 Answers

std::fputc(stdout, c); could simply be implemented in terms of std::cout << c; or the other way round (or using a common primitive)

It is actually "the other way round". The synchronized std::cout is an unbuffered stream, and each std::cout << c; immediately executes std::fputc(stdout, c);.

synchronized streams would even have an advantage over non-synchronized ones! Fewer buffers, fewer cache misses

It's just one buffer either way: stdout's when synchronized or std::cout's when not. On my gcc/libstdc++, the main difference is that one is 1024 bytes and the other is 8191 (seriously). It might be interesting to profile the three existing implementations of the standard library (libstdc++, libc++, and MSVC) to spot the differences and what causes them. It may very well be that they are "imperfect implementations" - there is no reason unsynchronized std::cout << c; should ever be slower than (always synchronized) std::fputc(stdout, c);.

like image 51
Cubbi Avatar answered Feb 17 '26 10:02

Cubbi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!