为什么 std::ios_base::sync_with_stdio 没有在 libc++ 中实现(clang)?
Why std::ios_base::sync_with_stdio isn't implemented in libc++ (clang)?
让我们看一下这个代码示例:
#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;
}
}
此代码示例在输入时的性能如下:
10000000
0
1
...
9999999
在我的机器上:
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
经过一些分析后,我发现 libc++ 根本没有禁用同步。
然后我查看了他们的代码,发现了这个:
https://github.com/llvm-mirror/libcxx/blob/6a85e8a355be05b9efa8408f875014e6b47cef3b/src/ios.cpp#L458
所以我的问题是,这是设计使然还是错误?
据我所知,sync_with_stdio
只是一个咨询功能。
ios.members.static/2 说:
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" 是关键,恕我直言。
没有要求实际执行此操作,而是禁止这样做除非已进行此调用。
所以,是的,这是合规行为。
让我们看一下这个代码示例:
#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;
}
}
此代码示例在输入时的性能如下:
10000000
0
1
...
9999999
在我的机器上:
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
经过一些分析后,我发现 libc++ 根本没有禁用同步。
然后我查看了他们的代码,发现了这个: https://github.com/llvm-mirror/libcxx/blob/6a85e8a355be05b9efa8408f875014e6b47cef3b/src/ios.cpp#L458
所以我的问题是,这是设计使然还是错误?
sync_with_stdio
只是一个咨询功能。
ios.members.static/2 说:
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" 是关键,恕我直言。
没有要求实际执行此操作,而是禁止这样做除非已进行此调用。
所以,是的,这是合规行为。