std::ios_base::sync_with_stdio 如何影响流缓冲?

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

this answer on Stack Overflow and cppreference.com 都建议关闭流同步以提高性能,认为流同步会禁用缓冲。

现在这是我不明白的地方。为什么同步流不能简单地共享缓冲区?我想象如果流是同步的,std::fputc(stdout, c); 可以简单地根据 std::cout << c; 或相反的方式(或使用通用原语)来实现。因此,每当 C I/O 与 C++ I/O 混合时,同步流甚至比非同步流更有优势!更少的缓冲区,更少的缓存未命中。

目前的C++标准草案似乎就在我这里。在指定 sync_with_stdio() 的脚注中,它说 "In practical terms, synchronization usually means that a standard iostream object and a standard stdio object share a buffer." 我上面发布的链接是否可能仅记录了一些不完善的实现及其性能影响?

另外,因为我没有看到非同步流有任何理论上的缺点,所以我想知道为什么这些首先存在。

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

其实是"the other way round"。 synchronized std::cout 是无缓冲流,每个 std::cout << c; 立即执行 std::fputc(stdout, c);.

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

这两种方式都只是一个缓冲区:stdout 同步时或 std::cout 不同步时。在我的 gcc/libstdc++ 上,主要区别在于一个是 1024 字节,另一个是 8191(严重)。剖析标准库的三个现有实现(libstdc++、libc++ 和 MSVC)以发现差异及其原因可能很有趣。很可能它们是 "imperfect implementations" - 没有理由不同步 std::cout << c; 应该比(始终同步)std::fputc(stdout, c);.

这本书里有一个完美的答案 that I recommend reading. According to that answer originally writen by Ionut, "If you disable the synchronization, then C++ streams are allowed to have their own independent buffers". It is also discussed here,我想是在第 11 章。