c++ - 为什么 GNU 并行扩展似乎会使算法变慢?

标签 c++ parallel-processing g++ stl-algorithm

我想遵循本指南: 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/

相关文章:

指向数组的指针的 C++ 指针

实现纯虚类的 C++ 实例集合

javascript - 通过javascript中的多重处理解密

javascript - 在 Node.js 中并行化任务

Python:优化数据帧处理

linux - g++ 将 .a 文件及其依赖项链接到静态 .so

c++ - 选择在 Windows 7 上无法正常工作

c++ - 为什么必须将参数强制转换为 const?

c++ - QPainter:仅绘制放大图像的可见区域

C++ 模板类静态常量变量成员作为映射键给出 undefined reference