在 C++ 中使用 <execution> 的标头的问题

Posted

技术标签:

【中文标题】在 C++ 中使用 <execution> 的标头的问题【英文标题】:Problem with using header of <execution> in c++ 【发布时间】:2021-02-09 23:31:13 【问题描述】:

我在 Windows 10 上安装了 gcc 10.2.0。所以,在这个最新版本的 gcc 中实现了。 问题是当我从以下链接复制示例代码时:https://docs.w3cub.com/cpp/algorithm/reduce,它说:std::execution 尚未声明。有什么想法吗?

#include <iostream>
#include <chrono>
#include <vector>
#include <numeric>
#include <execution>
 
int main()

    std::vector<double> v(10'000'007, 0.5);
 
    
        auto t1 = std::chrono::high_resolution_clock::now();
        double result = std::accumulate(v.begin(), v.end(), 0.0);
        auto t2 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double, std::milli> ms = t2 - t1;
        std::cout << std::fixed << "std::accumulate result " << result
                  << " took " << ms.count() << " ms\n";
    
 
    
        auto t1 = std::chrono::high_resolution_clock::now();
        double result = std::reduce(std::execution::par, v.begin(), v.end());
        auto t2 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double, std::milli> ms = t2 - t1;
        std::cout << "std::reduce result "
                  << result << " took " << ms.count() << " ms\n";
    

【问题讨论】:

您是否启用了 C++17 标志? 另外,请出示您的编译命令。 Works for me 也许这会有所帮助。 ***.com/questions/43689444/… @Movahedi-24 当然,多线程并不能保证提高性能。我还没有通读并行算法的标准实现,但是启动和销毁线程/线程池都会产生成本。此外,在并行情况下,您最终会做更多的工作,因为您必须将数据分块以供每个线程处理,然后在最后累积。您受到最慢线程的限制。所以同步和资源分时也需要考虑在内。如果你在每个线程中做更多的工作,你可能会开始看到更大的好处。 【参考方案1】:

为了向后兼容,许多编译器默认使用旧的 C++ 模式。在设置中启用 C++17 以使用更新的功能。

【讨论】:

以上是关于在 C++ 中使用 <execution> 的标头的问题的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 g++6 编译带有 std::reduce 和 #include <execution_policy> 的代码?

如何在 C++ (g++)中使用 A,B<=10^18 计算 Fibonacci(A) mod B [关闭]

使用 gcc/g++ 使 C++ 程序在没有窗口的情况下运行? [复制]

Couldn't find log associated with operation handle: OperationHandle [opType=EXECUTE_STATEMENT, g

为啥 g++ 需要 -fpermissive 标志来在 c++ 中打印迭代器值? [关闭]

c++中向量中的随机访问[重复]