【问题标题】:Parallel execution policies in C++ 17C++ 17 中的并行执行策略
【发布时间】:2019-04-06 05:12:45
【问题描述】:

我最近开始使用/学习 C++17 的一些新特性来实现并行性。

我遵循了或多或少改编自 C++17 食谱 (https://www.oreilly.com/library/view/c17-stl-cookbook/9781787120495/) 的代码(如下所列)。

但无论我使用 'execution::par' 还是 'execution::seq',执行时间似乎都没有区别(请参阅下面的输出)。

---代码---

#include <iostream>
#include <vector>
#include <random>
#include <algorithm>
#include <execution>
#include <ctime>

using namespace std;

static bool odd(int n) { return ((n % 2)==0); }

int main(int argc, char** argv)
{
    int arg1 = -1;
    if (argc == 2)
    {
        arg1 = atoi(argv[1]);
    }
    std::time_t result1 = std::time(nullptr);
    
    vector<int> d(50000000);

    mt19937 gen;
    uniform_int_distribution<int> dis(0, 100000);
    auto rand_num([=]() mutable { return dis(gen); });

    if (arg1 == 1)
    {
        generate(execution::par, begin(d), end(d), rand_num);

        auto odds(count_if(execution::par, begin(d), end(d), odd));
        cout << (100.0 * odds / d.size()) << "% of the numbers are odd.\n";
    }
    else if(arg1 == 2)
    {
        generate(execution::seq, begin(d), end(d), rand_num);

        auto odds(count_if(execution::seq, begin(d), end(d), odd));
        cout << (100.0 * odds / d.size()) << "% of the numbers are odd.\n";
    }   
    else
    {
        cout << "Missing argument..";
    }
    std::time_t result2 = std::time(nullptr);
    std::cout << "\t\n" << result2-result1 << " (seconds)\n";
}

我使用的是 Visual Studio 2017 版本 15.8.8。一些编译/构建选项如下:

/JMC /GS /Qpar /W3 /Zc:wchar_t /ZI /Gm- /Od /Zc:inline /fp:precise /D "_D​​EBUG" /D "_UNICODE" /D "UNICODE" /errorReport :prompt /WX- /Zc:forScope /RTC1 /Gd /MDd /std:c++latest /FC /EHsc /nologo /diagnostics:classic

----我得到的输出----

>stlpar.exe 1

49.9995% 的数字是奇数。

16(秒)

>stlpar.exe 2

49.9995% 的数字是奇数。

16(秒)

>

我希望使用参数 1 运行应该使用 execution::par 并且与使用切换到 'execution::seq' 的参数 2 运行时相比,时间应该明显减少。

【问题讨论】:

    标签: c++ parallel-processing c++17 execution


    【解决方案1】:

    在 VS 15.8 中,generatenot implemented as a parallel function。所以如果代码的时间以generate函数为主,那么你的示例代码的执行时间不会有显着差异。

    此外,使用高分辨率计时器也是一个好习惯:

    #include <chrono>
    using std::chrono::high_resolution_clock;
    

    【讨论】:

    • 谢谢 Phillip,Count_if 也一样吗?我希望 50000000 个元素至少有 1-2 秒的差异。
    • count_if 在该版本的 VS 中实现。但是,我希望随机数生成器在执行时间中占主导地位,因此即使奇数计算被并行化,总时间也不会明显减少。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2012-08-13
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    相关资源
    最近更新 更多