gpt4 book ai didi

c++ - 查找数组中的最小元素及其索引

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:35:29 25 4
gpt4 key购买 nike

使用 OpenMP 3.1,可以使用 minreduction 子句:

double m;
#pragma omp parallel for reduction(min:m)
for (int i=0;i< n; i++){
if (a[i]*2 < m) {
m = a[i] * 2;
}
return m;

假设我还需要最小元素的索引;有没有办法为此使用 reduction 子句?我相信替代方案是使用 nowaitcritical 手动编写缩减。

最佳答案

Suppose I also need the index of the minimal element; is there a way to use the reduction clause for this?

不幸的是,没有。 OpenMP 中可能减少的列表非常……小。特别是,minmax 是仅有的“高级”函数,它们不可自定义。完全没有。

我不得不承认,我不喜欢 OpenMP 的缩减方法,正是因为它根本不可扩展,它设计仅适用于特殊情况。诚然,这些都是有趣的特例,但从根本上说它仍然是一种糟糕的方法。

对于此类操作,您需要通过将线程局部结果累加到线程局部变量中并在最后组合它们来自行实现缩减。

执行此操作的最简单方法(实际上与 OpenMP 实现缩减的方式非常接近)是为每个线程创建一个包含元素的数组,并使用 omp_get_thread_num() 访问元素。但是请注意,如果数组中的元素共享缓存行,这将导致由于错误共享而导致的性能下降。为了缓解这种情况,填充数组:

struct min_element_t {
double min_val;
size_t min_index;
};

size_t const CACHE_LINE_SIZE = 1024; // for example.
std::vector<min_element_t> mins(threadnum * CACHE_LINE_SIZE);

#pragma omp parallel for
for (int i = 0; i < n; ++i) {
size_t const index = omp_get_thread_num() * CACHE_LINE_SIZE;
// operate on mins[index] …
}

关于c++ - 查找数组中的最小元素及其索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11242439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com