基于mpi实现矩阵乘法
时间: 2024-05-13 10:20:38 浏览: 16
以下是基于MPI实现矩阵乘法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define N 100
int main(int argc, char *argv[]) {
int rank, size;
int i, j, k;
int A[N][N], B[N][N], C[N][N];
int rowA[N], rowC[N];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (size != N) {
printf("Error: number of processes must be %d\n", N);
MPI_Finalize();
return 0;
}
// Initialize matrices A and B
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
A[i][j] = i + j;
B[i][j] = i - j;
C[i][j] = 0;
}
}
// Scatter matrix A to all processes
MPI_Scatter(A, N*N/N, MPI_INT, rowA, N, MPI_INT, 0, MPI_COMM_WORLD);
// Broadcast matrix B to all processes
MPI_Bcast(B, N*N, MPI_INT, 0, MPI_COMM_WORLD);
// Compute rows of matrix C
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
rowC[j] = 0;
for (k = 0; k < N; k++) {
rowC[j] += rowA[k] * B[k][j];
}
}
MPI_Reduce(rowC, &C[i], N, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
}
// Gather matrix C from all processes
MPI_Gather(rowC, N*N/N, MPI_INT, C, N*N/N, MPI_INT, 0, MPI_COMM_WORLD);
// Print matrix C
if (rank == 0) {
printf("Matrix C:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
}
MPI_Finalize();
return 0;
}
```
该程序将矩阵A均分给所有进程,每个进程计算矩阵C的一行。使用MPI_Reduce函数将每个进程计算出的行向量相加,得到最终的矩阵C。最后,使用MPI_Gather函数将矩阵C收集到进程0中,并打印输出。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)