【发布时间】: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 "_DEBUG" /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