【发布时间】:2016-10-29 12:20:03
【问题描述】:
问:是否可以在 OS X 下使用 LLVM Clang 改进这段代码的 IO:
test_io.cpp:
#include <iostream>
#include <string>
constexpr int SIZE = 1000*1000;
int main(int argc, const char * argv[]) {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::string command(argv[1]);
if (command == "gen") {
for (int i = 0; i < SIZE; ++i) {
std::cout << 1000*1000*1000 << " ";
}
} else if (command == "read") {
int x;
for (int i = 0; i < SIZE; ++i) {
std::cin >> x;
}
}
}
编译:
clang++ -x c++ -lstdc++ -std=c++11 -O2 test_io.cpp -o test_io
基准测试:
> time ./test_io gen | ./test_io read
real 0m2.961s
user 0m3.675s
sys 0m0.012s
除了读取 10MB 文件需要 3 秒这一可悲的事实之外,它远比 g++(通过自制软件安装)慢:
> gcc-6 -x c++ -lstdc++ -std=c++11 -O2 test_io.cpp -o test_io
> time ./test_io gen | ./test_io read
real 0m0.149s
user 0m0.167s
sys 0m0.040s
我的 clang 版本是 Apple LLVM version 7.0.0 (clang-700.0.72)。从自制软件(3.7 和 3.8)安装的clangs 也会产生缓慢的 io。 clang 安装在 Ubuntu (3.8) 上会生成快速 io。 Apple LLVM version 8.0.0 产生缓慢的 io(2 人问)。
我还对其进行了一些处理 (sudo dtruss -c "./test_io gen | ./test_io read"),发现 clang 版本产生了 2686 个write_nocancel 系统调用,而 gcc 版本产生了 2079 个writev 系统调用。这可能指向问题的根源。
【问题讨论】:
-
你试过-O3
-
如果你将 clang 编译版本的输出输入 gcc 编译版本,它仍然非常快,但是如果你将 gcc 编译版本输入 clang 编译版本,它会得到慢 - 所以我推断它是铿锵声慢的阅读。如果您将输出的字符从空格更改为
X,它们都很快并且速度大致相同。
标签: c++ macos llvm llvm-clang