我想遵循本指南: http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt12ch31s03.html
这里是一些示例代码:
#include <numeric>
#include <vector>
#include <iostream>
#include <chrono>
using namespace std;
int main()
{
vector<int> in(1000);
vector<double> out(1000);
iota(in.begin(), in.end(), 1);
auto t = std::chrono::high_resolution_clock::now();
for(int i = 0; i < 100000; ++i)
accumulate(in.begin(), in.end(), 0);
auto t2 = std::chrono::high_resolution_clock::now();
cout << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t).count() << endl;
return 0;
}
我得到以下结果:
~:$ g++ test.cpp -std=c++11
~:$ ./a.out
900
~:$ g++ test.cpp -D_GLIBCXX_PARALLEL -std=c++11 -fopenmp -march=native
~:$ ./a.out
1026
当进行多次运行时,这两个时间大约保持在同一时间。 我还尝试过其他算法,例如排序、生成、查找、转换...... 我有一个 i7,启用了超线程(4 个逻辑核心)。 我运行 g++-4.8.1
谢谢
最佳答案
我认为你需要尝试一些更重的东西。您所做的就是将 int
添加在一起。创建线程等的开销会更大。尝试将 int
替换为 std::string
并运行以下代码并比较输出:
int main()
{
vector<string> in(100000);
auto t = std::chrono::high_resolution_clock::now();
accumulate(in.begin(), in.end(), string(), [](string s1, string s2){ return s1 += s2 + "a" + "b";});
auto t2 = std::chrono::high_resolution_clock::now();
cout << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t).count() << endl;
}
关于c++ - 为什么 GNU 并行扩展似乎会使算法变慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17830362/