使用OpenMP的数组中的最大值 [英] Max value in an array using OpenMP

查看:79
本文介绍了使用OpenMP的数组中的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须解决有关OpenMP的练习;在这里:

I have to solve an exercise about OpenMP; here it is:

编写如下的OpenMP代码(所需的最小代码片段):接受整数数组A(大小为NUM),并填充数组B(浮点数),其值B [i] = A [i]/MaxA(必须将MaxA计算为所提供的代码的一部分).

Write the OpenMP code (the minimal fragment of code you need) that takes an array A of integers (of size NUM) and fills an array B (of floats) with the values B[i]=A[i]/MaxA (MaxA must be calculated as part of the provided code).

对于最终的计算,我将使用

For the final calculation I would use

#pragma omp parallel for shared(A,B)
for(int i=0; i<NUM; i++) {
   B[i] = A[i]/MaxA;
}

我的疑问在于如何利用OpenMP来计算A的最大值.

My doubt is on how to take advantage of OpenMP to compute the maximum value of A.

我想到的唯一想法是使用并行部分并行化递归最大计算:

The only idea I came up with is using parallel sections to parallelize a recursive maximum computation:

第一个呼叫是i = 0;j = sizeOfA-1

The first call is made with i=0; j= sizeOfA - 1

int max(int A[], int i, int j) {

    // Leaves conditions
    switch (j-i) {
        case 1:
        {   if( A[i]>A[j] )
                return A[i];
            else
                return A[j];
        }
                break;
        case 0:
            return A[i];
            break;
    }


    int left, right;
    #pragma omp parallel sections
    {
        #pragma omp section
        {
            left = max( A, i, i+(j-i)*0.5);
        }

        #pragma omp section
        {
            right = max( A, i+(j-i)*0.5+1, j);

        }
    }

    // Nodes conditions
    if( right > left )
        return right;
    else
        return left;

}

您认为这是一个很好的解决方案吗?你能告诉我是否有更好的解决方案/替代方法?

Do you think it is a good solution? Can you tell me if there is any better solution / alternative ?

推荐答案

如何使用归约子句来计算[i,j]之间范围内A内的最大值,而不是使用递归计算?

What about using a reduction clause to calculate the maximum value within A in the range between [i,j] instead of using recursive calculation?

类似

int max(int A[], int i, int j)
{
    int idx;
    int max_val; /* = 0 not needed according to Jim Cownie comment */

    #pragma omp parallel for reduction(max:max_val) 
    for (idx = i; idx < j; idx++)
       max_val = max_val > A[idx] ? max_val : A[idx];

    return max_val;
}

这篇关于使用OpenMP的数组中的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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