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

Parallel execution policies in C++ 17

本文关键字:策略 并行执行 C++17      更新时间:2023-10-16

我最近开始使用/学习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 << "tn" << 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"_DEBUG"/D"_UNICODE"/D";UNICODE"/错误报告:提示/WX-/Zc:forScope/RTC1/Gd/MDd/std:c++最新/FC/EHsc/nologo/defaults:classic

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

>stlpar.exe 1

49.9995%的数字是奇数。

16(秒(

>stlpar.exe 2

49.9995%的数字是奇数。

16(秒(

>

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

在VS 15.8中,generate不是作为并行函数实现的。因此,如果代码的时间由generate函数支配,那么示例代码的执行时间将不会有显著差异。

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

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