导入
理解并行算法
理解顺序执行与并行执行之间的概念差异,并学习何时利用标准库算法来自动使用多核硬件。
1#include <algorithm> 2#include <execution> // Required for execution policies 3#include <vector> 4#include <iostream> 5#include <random> 6 7int main() { 8 // Generate a large dataset 9 std::vector<int> data(1'000'000); 10 std::generate(data.begin(), data.end(), std::rand); 11 12 std::vector<int> data_seq = data; 13 std::vector<int> data_par = data; 14 15 // 1. Sequential Sort (The default) 16 // The algorithm runs on a single thread 17 std::sort(data_seq.begin(), data_seq.end()); 18 19 // 2. Parallel Sort (Declarative) 20 // By adding std::execution::par, we request parallel execution 21 // The library handles thread creation and data partitioning internally 22 std::sort(std::execution::par, data_par.begin(), data_par.end()); 23 24 if (std::equal(data_seq.begin(), data_seq.end(), data_par.begin())) { 25 std::cout << "Both strategies produced the same sorted result.\n"; 26 } 27 28 return 0; 29}