gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:28 25 4
gpt4 key购买 nike

我想并行化这个函数,但我是 open 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;
}
}

由于双循环,我不知道如何正确并行化它,因为目前,我只想做一个: #pragma omp parallel for reduction(+:t)

但我认为这不是通过 openMp 加快计算速度的最佳方式。

提前致谢

最佳答案

首先:我们需要了解上下文。你的探查器告诉你最多的时间花在哪里?

一般来说,粗粒度并行化效果最好,所以正如@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;
}
}

根据实际体积,在后台计算 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;
}
}
}
}

注意 未经测试的代码。 OMP 有时有棘手的语义,所以我可能错过了那里的“共享”声明。不过,分析器不会很快通知您。

关于c++ - OpenMP C++ - 如何并行化这个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12143911/

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