[英]OpenMP C++ - How to parallelize this function?
我想將這個功能並行化,但我是開放式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有時會有棘手的語義,所以我可能錯過了那里的“共享”聲明。 但是,探查器不會很快通知您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.