简体   繁体   English

OpenMP C ++ - 如何并行化这个函数?

[英]OpenMP C++ - How to parallelize this function?

I'd like to parallelize this function but I'm new with open mp and I'd be grateful if someone could help me : 我想将这个功能并行化,但我是开放式mp的新手,如果有人能帮助我,我将不胜感激:

void my_function(float** A,int nbNeurons,int nbOutput, float* p, float* amp){
   float t=0;
   for(int r=0;r<nbNeurons;r++){
      t+=p[r];
   }

   for(int i=0;i<nbOutput;i++){
      float coef=0;
      for(int r=0;r<nbNeurons;r++){
       coef+=p[r]*A[r][i];
      }
   amp[i]=coef/t;
   }
}

I don't know how to parallelize it properly because of the double loop for, for the moment, I only thought about doing a : #pragma omp parallel for reduction(+:t) 我不知道如何正确地并行化,因为双循环,目前,我只考虑做一个: #pragma omp parallel for reduction(+:t)

But I think it is not the best way to get the computing faster through openMp. 但我认为这不是通过openMp更快地实现计算的最佳方式。

Thank in advance, 预先感谢,

First of all: we need to know context. 首先:我们需要了解背景。 Where does your profiler tell you the most time is spent? 您的探查器在哪里告诉您花费的时间最多?

In general, coarse grained parallellization works best, so as @Alex said: parallellize the outer for loop. 一般来说,粗粒度并行化效果最好,因为@Alex说:并行外部for循环。

void my_function(float** A,int nbNeurons,int nbOutput, float* p, float* amp)
{
    float t=0;
    for(int r=0;r<nbNeurons;r++)
        t+=p[r];

#pragma parallel omp for 
    for(int i=0;i<nbOutput;i++){
        float coef=0;
        for(int r=0;r<nbNeurons;r++){
            coef+=p[r]*A[r][i];
        }
        amp[i]=coef/t;
    }
}

Depending on the actual volumes, it may be interesting to calculate t in the background, and move the division out of the parallel loop: 根据实际的体积,在后台计算t并将分区移出并行循环可能会很有趣:

void my_function(float** A,int nbNeurons,int nbOutput, float* p, float* amp)
{
    float t=0;
#pragma omp parallel shared(amp)
    {
#pragma omp single nowait // only a single thread executes this
        {
            for(int r=0;r<nbNeurons;r++)
                t+=p[r];
        }

#pragma omp for 
        for(int i=0;i<nbOutput;i++){
            float coef=0;
            for(int r=0;r<nbNeurons;r++){
                coef+=p[r]*A[r][i];
            }
            amp[i]=coef;
        }

#pragma omp barrier
#pragma omp master // only a single thread executes this
        {
            for(int i=0; i<nbOutput; i++){
                amp[i] /= t;
            }
        }
    }
}

Note untested code. 注意未经测试的代码。 OMP has tricky semantics sometimes, so I might have missed a 'shared' declaration there. OMP有时会有棘手的语义,所以我可能错过了那里的“共享”声明。 Nothing a profiler won't quickly notify you about, though. 但是,探查器不会很快通知您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM