Run STL algorithms in parallel with execution policies
Beginning with C++17, many of the standard STL algorithms can run with parallel execution. This feature allows an algorithm to split its work into sub-tasks to run simultaneously on multiple cores. These algorithms accept an execution policy object that specifies the kind of parallelism applied to the algorithm. This feature requires hardware support.
How to do it…
Execution policies are defined in the <execution>
header and in the std::execution
namespace. In this recipe, we will test the available policies using the std::transform()
algorithm:
- For timing purposes, we'll use the
duration
object with thestd::milli
ratio so that we can measure in milliseconds:using dur_t = duration<double, std::milli>;
- For demonstration purposes, we'll start with a
vector
ofint
with 10 million random values:int main() { std::vector<unsigned> v(10 * 1000 * 1000); ...