std::execution::seq, std::execution::par, std::execution::par_unseq, std::execution::unseq
来自cppreference.com
在标头 <execution> 定义 | ||
inlineconstexpr std::execution::sequenced_policy seq {/* 未指明 */}; | (C++17 起) | |
inlineconstexpr std::execution::parallel_policy par {/* 未指明 */}; | (C++17 起) | |
inlineconstexpr std::execution::parallel_unsequenced_policy par_unseq {/* 未指明 */}; | (C++17 起) | |
inlineconstexpr std::execution::unsequenced_policy unseq {/* 未指明 */}; | (C++20 起) | |
各执行策略类型
- std::execution::sequenced_policy,
- std::execution::parallel_policy,
- std::execution::parallel_unsequenced_policy,和
- std::execution::unsequenced_policy
相应的有以下实例:
std::execution::seq
,std::execution::par
,std::execution::par_unseq
,和std::execution::unseq
。
这些实例用于指定并行算法的执行策略——即允许采用何种并行运算。
标准库的实现可以提供附加的执行策略。(可能的未来额外策略包含 std::parallel::cuda
和 std::parallel::opencl
)
[编辑]示例
运行此代码
#include <algorithm>#include <chrono>#include <cstdint>#include <iostream>#include <random>#include <vector> #ifdef PARALLEL#include <execution>namespace execution = std::execution;#elseenumclass execution { seq, unseq, par_unseq, par };#endif void measure([[maybe_unused]]auto policy, std::vector<std::uint64_t> v){constauto start =std::chrono::steady_clock::now();#ifdef PARALLELstd::sort(policy, v.begin(), v.end());#elsestd::sort(v.begin(), v.end());#endifconstauto finish =std::chrono::steady_clock::now();std::cout<<std::chrono::duration_cast<std::chrono::milliseconds>(finish - start)<<'\n';}; int main(){std::vector<std::uint64_t> v(1'000'000);std::mt19937 gen {std::random_device{}()}; std::ranges::generate(v, gen); measure(execution::seq, v); measure(execution::unseq, v); measure(execution::par_unseq, v); measure(execution::par, v);}
可能的输出:
// 在线 GNU/gcc 编译器 (未定义 PARALLEL 宏) 81ms 80ms 79ms 78ms // 编译为 g++ -std=c++23 -O3 ./test.cpp -ltbb -DPARALLEL 165ms 163ms 30ms 27ms
[编辑]参阅
(C++17)(C++17)(C++17)(C++20) | 执行策略类型 (类) |