Performance Comparison between Execution Policies
We can compare the performance difference between the execution policies using a simple C++ program as shown below:
C++
// C++ Program to evaluate the performance of the four // execution policies #include <chrono> #include <execution> #include <iostream> #include <vector> // Function to calculate the execution time of different // execution policies void execTime( auto policy_type, std::vector< int >& num, std::string pType_name) { auto start_time = std::chrono::high_resolution_clock::now(); long long sum = 0; // finding sum of each element in the vector std::for_each(policy_type, num.begin(), num.end(), [&]( int n) { sum += n; }); auto end_time = std::chrono::high_resolution_clock::now(); auto taken_time = std::chrono::duration_cast< std::chrono::milliseconds>( end_time - start_time) .count(); // printing execution time std::cout << pType_name << " execution time: " << taken_time << "ms\n" ; } int main() { // Creating large vector of int int size = 9999999; std::vector< int > num(size); // initializing vector for ( int i = 0; i < size; i++) { num[i] = i; } // execution time execTime(std::execution::seq, num, "Sequenced" ); execTime(std::execution::unseq, num, "Unsequenced" ); execTime(std::execution::par, num, "Parallel" ); execTime(std::execution::par_unseq, num, "Parallel Unsequenced" ); return 0; } |
Output
Sequenced execution time: 917ms Unsequenced execution time: 406ms Parallel execution time: 897ms Parallel Unsequenced execution time: 420ms
As we can see, of all the execution policies, the unsequenced_policy is the fastest because of vectorization. Then comes parallel_unsequenced_policy followed by the parallel_policy. At last, we sequenced the execution method as expected.
Note: The above code can only be executed using C++20 Standard or above compiler.
Execution Policy of STL Algorithms in Modern C++
C++ algorithms are a set of pre-defined functions that can perform various operations on containers, such as arrays, vectors, and lists. These algorithms have a defined execution policy that determines how they execute and how they interact with the underlying hardware.
The C++ 17 standard introduces three new execution policies and one policy was introduced in C++20. These execution policies in C++ allow algorithms to be executed in different ways depending on the requirements of the task and the hardware available. They are as follows:
- std::execution::sequenced_policy
- std::execution::parallel_policy
- std::execution::parallel_unsequenced_policy
- std::execution::unsequenced_policy