|
|
|
|
|
|
|
#include <mpi.h> |
|
#include <stdio.h> |
|
#include <stdlib.h> |
|
#include <time.h> |
|
|
|
int main(int argc, char *argv[]) { |
|
MPI_Init(&argc, &argv); |
|
int size, rank; |
|
MPI_Comm_size(MPI_COMM_WORLD, &size); |
|
MPI_Comm_rank(MPI_COMM_WORLD, &rank); |
|
|
|
int N = 8000; |
|
if (argc >= 2) { |
|
N = atoi(argv[1]); |
|
} |
|
|
|
int base = N / size; |
|
int rem = N % size; |
|
int local_rows = base + (rank < rem ? 1 : 0); |
|
|
|
|
|
int *sendcounts = NULL, *displs = NULL; |
|
if (rank == 0) { |
|
sendcounts = malloc(size * sizeof(int)); |
|
displs = malloc(size * sizeof(int)); |
|
int offset = 0; |
|
for (int i = 0; i < size; i++) { |
|
int rows = base + (i < rem ? 1 : 0); |
|
sendcounts[i] = rows * N; |
|
displs[i] = offset * N; |
|
offset += rows; |
|
} |
|
} |
|
|
|
|
|
double *A_local = malloc((size_t)local_rows * N * sizeof(double)); |
|
double *B = malloc((size_t)N * N * sizeof(double)); |
|
double *C_local = malloc((size_t)local_rows * N * sizeof(double)); |
|
if (!A_local || !B || !C_local) { |
|
fprintf(stderr, "进程 %d: 内存分配失败\n", rank); |
|
MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); |
|
} |
|
|
|
|
|
double *A = NULL; |
|
if (rank == 0) { |
|
A = malloc((size_t)N * N * sizeof(double)); |
|
srand(0); |
|
for (long long i = 0; i < (long long)N * N; i++) { |
|
A[i] = rand() / (double)RAND_MAX; |
|
B[i] = rand() / (double)RAND_MAX; |
|
} |
|
} |
|
|
|
|
|
MPI_Scatterv(A, sendcounts, displs, MPI_DOUBLE, |
|
A_local, local_rows * N, MPI_DOUBLE, |
|
0, MPI_COMM_WORLD); |
|
|
|
MPI_Bcast(B, N * N, MPI_DOUBLE, 0, MPI_COMM_WORLD); |
|
|
|
|
|
MPI_Barrier(MPI_COMM_WORLD); |
|
double t0 = MPI_Wtime(); |
|
|
|
for (int i = 0; i < local_rows; i++) { |
|
for (int j = 0; j < N; j++) { |
|
double sum = 0.0; |
|
for (int k = 0; k < N; k++) { |
|
sum += A_local[(long long)i * N + k] * B[(long long)k * N + j]; |
|
} |
|
C_local[(long long)i * N + j] = sum; |
|
} |
|
} |
|
|
|
MPI_Barrier(MPI_COMM_WORLD); |
|
double t1 = MPI_Wtime(); |
|
double local_elapsed = t1 - t0; |
|
double max_elapsed; |
|
|
|
|
|
MPI_Reduce(&local_elapsed, &max_elapsed, 1, MPI_DOUBLE, |
|
MPI_MAX, 0, MPI_COMM_WORLD); |
|
|
|
if (rank == 0) { |
|
printf("Parallel multiplication time: %.6f seconds with %d processes\n", |
|
max_elapsed, size); |
|
} |
|
|
|
|
|
free(A_local); |
|
free(B); |
|
free(C_local); |
|
if (rank == 0) { |
|
free(A); |
|
free(sendcounts); |
|
free(displs); |
|
} |
|
MPI_Finalize(); |
|
return 0; |
|
} |
|
|