Namespaces
Variants

std::execution:: seq, std::execution:: par, std::execution:: par_unseq, std::execution:: unseq

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
execution::seq execution::par execution::par_unseq execution::unseq
(C++17) (C++17) (C++17) (C++20)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
定义于头文件 <execution>
inline constexpr
std:: execution :: sequenced_policy seq { /* 未指定 */ } ;
(C++17 起)
inline constexpr
std:: execution :: parallel_policy par { /* 未指定 */ } ;
(C++17 起)
inline constexpr
std:: execution :: parallel_unsequenced_policy par_unseq { /* 未指定 */ } ;
(C++17 起)
inline constexpr
std:: execution :: unsequenced_policy unseq { /* 未指定 */ } ;
(C++20 起)

执行策略类型

具有以下各自的实例:

  • 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;
#else
    enum class execution { seq, unseq, par_unseq, par };
#endif
void measure([[maybe_unused]] auto policy, std::vector<std::uint64_t> v)
{
    const auto start = std::chrono::steady_clock::now();
#ifdef PARALLEL
    std::sort(policy, v.begin(), v.end());
#else
    std::sort(v.begin(), v.end());
#endif
    const auto 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

参见

执行策略类型
(类)