【问题标题】:Why does GNU Parallel extensions seems to make algorithms go slower?为什么 GNU Parallel 扩展似乎让算法变得更慢?
【发布时间】:2013-07-24 09:40:34
【问题描述】:

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

谢谢

【问题讨论】:

  • 请记住,创建线程以及操作系统在它们之间切换时存在开销。对于像你这样的小循环,开销可能很大,你应该尝试使用更大的数据集(即循环更多)。

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


【解决方案1】:

我认为你需要尝试一些更重的东西。您所做的就是将ints 加在一起。创建线程等的开销会更大。尝试将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;
}

【讨论】:

  • 附带说明,如果有人对 g++ 提供的获胜数量感兴趣,我会得到这些数字:* 没有并行扩展:530 毫秒(平均)* 没有并行和 O3:500 毫秒 *并行:95 毫秒 * 并行和 O3:85 毫秒
猜你喜欢
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多