gpt4 book ai didi

c++ - C++ 17 中的并行执行策略

转载 作者:行者123 更新时间:2023-11-28 01:27:35 25 4
gpt4 key购买 nike

我最近开始使用/学习 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% of the numbers are odd.

16 (seconds)

>stlpar.exe 2

49.9995% of the numbers are odd.

16 (seconds)

>

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

最佳答案

在 VS 15.8 中 generatenot implemented as a parallel function .因此,如果代码的时间由 generate 函数支配,则示例代码的执行时间不会有显着差异。

此外,使用高分辨率计时器也是一种很好的做法:

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

关于c++ - C++ 17 中的并行执行策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53110423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com