简体   繁体   English

矩阵乘法并行实现(OpenMP)

[英]matrix multiplication Parallelized implementation (OpenMP)

I ran a matrix multiplication code serially and parallelized.There was no significant improvement with the parallel version. 我对矩阵乘法代码进行了串行和并行化处理。并行版本没有明显的改进。

    dimension =4000;

    //#pragma omp parallel for shared(A,B,C) private(i,j,k)
    {
    for(int i=0; i<dimension; i++){
        for(int j=0; j<dimension; j++){
           for(int k=0; k<dimension; k++){
             C[i][j] += A[i][k] * B[k][j];
            }
        }       
    }
    }

Output: time ./a.out 输出:time ./a.out

real    4m58,760s
user    4m58,706s
sys     0m0,036s

for serial code (I put the #pragma... in a comment,rest of code is same) I got following output 对于串行代码(我在注释中加入了#pragma ...,其余代码相同),我得到了以下输出

real    4m51,240s
user    4m51,210s
sys     0m0,024s

You need to compile code with -fopenmp for the pragma to work. 您需要使用-fopenmp编译代码-fopenmp使编译指示起作用。 Also, you don't need to comment the pragma to run without OpenMP, just don't compile with OpenMP. 另外,您无需注释该实用程序即可在没有OpenMP的情况下运行,而无需使用OpenMP进行编译。

With OpenMP: gcc -fopenmp -o a.out code.c 使用OpenMP: gcc -fopenmp -o a.out code.c
Without OpenMP: gcc -o a.out code.c 没有OpenMP: gcc -o a.out code.c

Unless this is a (poorly chosen) educational example, please don't write your own matrix multiply and parallelize it. 除非这是一个(选择不佳)的教育示例,否则请不要编写自己的矩阵乘以并并行化它。 Getting near optimal performance from matrix multiplication involves other optimizations (vectorization, cache-blocking) which take time to get write and are hard to get correct. 从矩阵乘法获得接近最佳性能还涉及其他优化(矢量化,缓存块),这些优化需要时间来进行写入,而很难获得正确的结果。

As ever, "The best code is the code I don't have to write", so go grab a copy of a BLAS library (for instance, Intel MKL is now free). 与以往一样,“最好的代码是我不必编写的代码”,因此,请获取BLAS库的副本(例如, 英特尔MKL现在免费)。

I know it's more fun to write code than read a manual, but sometimes the latter is more productive! 我知道编写代码比阅读手册更有趣,但是有时后者会更有效率!

Full disclosre: I work for Intel, but not on MKL. 完全公开:我为Intel工作,但不在MKL工作。

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

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