减少最大值并保存其索引 [英] Reducing the max value and saving its index

查看:73
本文介绍了减少最大值并保存其索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int v[10] = {2,9,1,3,5,7,1,2,0,0};
int maximo = 0;
int b = 0;
int i;

#pragma omp parallel for shared(v) private(i) reduction(max:maximo)
for(i = 0; i< 10; i++){
    if (v[i] > maximo)
        maximo = v[i];
    b = i + 100;
}

ma​​ximo 获得其最大值(因此,它在 for 循环之后的值)时,我如何获得 b 在迭代期间获得的值?

How can I get the value that b gets during the iteration when maximo gets its max value (and therefore, its value after the for loop)?

推荐答案

TL;DR可以使用用户定义的减少.

首先,而不是:

for(i = 0; i< 10; i++){
    if (v[i] > maximo)
        maximo = v[i];
    b = i + 100;
}

你的意思是:

for(i = 0; i< 10; i++){
    if (v[i] > maximo){
        maximo = v[i];
        b = i + 100;
    }
}

OpenMP 具有考虑单个目标值的内置缩减函数,但是在您的情况下,您希望将 max 和数组索引这两个值考虑在内进行缩减.OpenMP 4.0 之后可以创建自己的归约函数( 用户定义的减少).

OpenMP has in-build reduction functions that consider a single target value, however in your case you want to reduce taking into account 2 values the max and the array index. After OpenMP 4.0 one can create its own reduction functions (i.e., User-Defined Reduction).

首先,创建一个结构体来存储两个相关的值:

First, create a struct to store the two relevant values:

struct MyMax {
   int max;
   int index;
};

然后我们需要OpenMP实现如何减少它:

then we need to teach the OpenMP implementation how to reduce it:

#pragma omp declare reduction(maximo : struct MyMax : omp_out = omp_in.max > omp_out.max ? omp_in : omp_out)

我们相应地设置平行区域:

we set our parallel region accordingly:

    #pragma omp parallel for reduction(maximo:myMaxStruct)
    for(int i = 0; i< 10; i++){
       if (v[i] > myMaxStruct.max){
          myMaxStruct.max = v[i];
          myMaxStruct.index = i + 100;
      }
   }

旁注你并不真的需要private(i),因为使用#pragma omp parallel for的索引变量em>for 循环无论如何都是隐式私有的.

Side Note You do not really need private(i), because with the #pragma omp parallel for the index variable of the for loop will be implicitly private anyway.

全部放在一起:

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

struct MyMax {
   int max;
   int index;
};


int main(void)
{
    #pragma omp declare reduction(maximo : struct MyMax : omp_out = omp_in.max > omp_out.max ? omp_in : omp_out)
    struct MyMax myMaxStruct;
    myMaxStruct.max = 0;
    myMaxStruct.index = 0;

    int v[10] = {2,9,1,3,5,7,1,2,0,0};

    #pragma omp parallel for reduction(maximo:myMaxStruct)
    for(int i = 0; i< 10; i++){
       if (v[i] > myMaxStruct.max){
          myMaxStruct.max = v[i];
          myMaxStruct.index = i + 100;
      }
   }
   printf("Max %d : Index %d\n", myMaxStruct.max, myMaxStruct.index);
}

输出:

Max 9 : Index 101

(索引为 101 因为你有 b = i + 100)

(Index is 101 because you have b = i + 100)

这篇关于减少最大值并保存其索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆