Search code examples
c++performancec++11clanglibc++

Why std::ios_base::sync_with_stdio isn't implemented in libc++ (clang)?


Let's look on this code example:

#include <iostream>

int main() {
    std::ios_base::sync_with_stdio(false);

    int n;
    std::cin >> n;
    for (int i = 0; i < n; ++i) {
        int buf;
        std::cin >> buf;
    }
}

Performance of this code sample on input like this:

10000000
0
1
...
9999999

on my machine:

g++-5 -O2 -std=c++11:

./a.out < input.txt  0.86s user 0.07s system 98% cpu 0.942 total

clang-700.0.72 -O2 -std=c++11:

./a.out < input.txt  38.69s user 0.21s system 99% cpu 39.248 total

After some profiling I found that libc++ doesn't disable synchronization at all.

Then I look at their code and found this: https://github.com/llvm-mirror/libcxx/blob/6a85e8a355be05b9efa8408f875014e6b47cef3b/src/ios.cpp#L458

So my question, is it by design or bug?


Solution

  • sync_with_stdio is just an advisory function, as far as I can tell.

    ios.members.static/2 says:

    Effects: If any input or output operation has occurred using the standard streams prior to the call, the effect is implementation-defined. Otherwise, called with a false argument, it allows the standard streams to operate independently of the standard C streams.

    "allows ... to operate independently" is the key, IMHO.

    There's no requirement on an implementation to actually do so, but rather, a prohibition on doing so unless this call has been made.

    So, yes, this is conforming behavior.