简体   繁体   English

每个向量的乘法矩阵

[英]Multiplication matrix per Vector

Any idea how to parallel this function using OpenMP?知道如何使用 OpenMP 并行这个 function 吗?

/*______ prod_matrix_vector __________ */

void dot(double matrix[], double vector[],int n, double result[]){
      
      for(int i=0,k=0;i<n*n,k<n;i=i+n,k++)
            for(int j=i,l=0;j<i+n,l<n;j++,l++)
                result[k]+=matrix[j]*vector[l];
}

The natural candidate for the parallelism is the outer loop, however, because it has two variable used to iterate ( ie, i and k ), we can not simply parallelized like it is using OpenMP.并行性的自然候选者是外循环,但是,因为它有两个用于迭代的变量(ik ),我们不能像使用 OpenMP 那样简单地并行化。

Therefore, we first need to re-arrange the outer loop so that it contains only one variable.因此,我们首先需要重新安排外循环,使其只包含一个变量。 Let us choose the variable k since it is used to iterate over the array result .让我们选择变量k ,因为它用于迭代数组result It is important to be the variable used to iterate over the array result because it is the only array being written into.成为用于迭代数组result的变量很重要,因为它是唯一被写入的数组。 Hence, it is the one that makes the more sense to distribute the iteration over that array among threads.因此,将迭代分布在线程之间的数组上更有意义。

If one runs your double loop (with an=4) and instead of result[k]+=matrix[j]*vector[l];如果一个人运行你的双循环(an=4)而不是result[k]+=matrix[j]*vector[l]; prints the values of i, k and j , one gets the following:打印i, k and j的值,得到以下结果:

i=0 k=0 j=0
i=0 k=0 j=1
i=0 k=0 j=2
i=0 k=0 j=3
i=4 k=1 j=4
i=4 k=1 j=5
i=4 k=1 j=6
i=4 k=1 j=7
i=8 k=2 j=8
i=8 k=2 j=9
i=8 k=2 j=10
i=8 k=2 j=11
i=12 k=3 j=12
i=12 k=3 j=13
i=12 k=3 j=14
i=12 k=3 j=15

So i = k * n;所以i = k * n;

So your double loop it is equivalent to:所以你的双循环相当于:

  for(int k=0; k<n; k++){
    int i = k * n;
    for(int j=i, l=0; j <i+n, l<n; j++,l++)
         result[k]+=matrix[j]*vector[l];
  }

now the outer loop can parallelized with OpenMP, namely:现在外循环可以与 OpenMP 并行化,即:

  #pragma omp parallel for
  for(int k=0; k<n; k++){
      for(int j= k * n, l=0; l<n; j++,l++)
         result[k] += matrix[j] * vector[l];
  }

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

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