c++ - C ++ 17中数组索引范围的并行for循环
问题描述
我需要更新一个 100M 元素的数组,并希望并行执行。 std::for_each(std::execution::par, ...)
这似乎很好,除了更新需要根据我正在更新的索引访问其他数组的元素。我试图并行化的那种东西的最小串行工作示例可能如下所示:
for (size_t i = 0; i < 100'000'000; i++)
d[i] = combine(d[i], s[2*i], s[2*i+1]);
我当然可以手动生成线程,但这比 更多的代码std::for_each
,所以很高兴找到一种优雅的方法来使用标准库执行此操作。到目前为止,我发现了一些不太优雅的使用方式for_each
,例如:
通过对数组元素的地址使用指针算法来计算索引。
本着 boost 的精神实现我自己的虚假迭代器
counting_range
。
有一个更好的方法吗?
解决方案
std::ranges
如果您可以访问 c++20,应该能够提供帮助,您可以迭代索引而不是数据:
#include <ranges>
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> d(100);
std::ranges::iota_view indexes((size_t)0, d.size());
std::for_each(indexes.begin(), indexes.end(), [&d](size_t i)
{
std::cout << i << "," << d[i] << "\n";
});
return 0;
}
推荐阅读
- swiftui - 添加视图时,SwiftUI 插入转换不起作用
- python - 如何在 Saleor Commerce 中创建新对象?
- python - 地球上两个圆(给定中心和半径的坐标)的交点坐标(纬度/经度)
- react-native - 我如何将 ref 传递给 state?
- wso2 - 从自定义 DNS 访问 Wso2 Api Manager
- c++ - int &p= n; 有什么不同?int *q = &n;?
- javascript - 苹果商店 - 反应原生二进制被拒绝
- ubuntu - Plesk 安装配置 PSA 数据库
- android - 如何在android的片段uisng约束布局中动态添加editText
- android - 模拟器:撤销 Google App 的麦克风权限