下面是一个完整的程序,可以满足您的要求。有几个问题会阻止原始版本工作:
- 标签不匹配,这将导致程序停止。
- 没有检查 MPI_COMM_WORLD 是否正好包含 2 个 MPI 进程,这也会导致停顿。
- 如果命令行上没有参数,您可能会遇到段错误。我为 . 添加了一个默认值
n
。
- 计时不会产生任何有用的东西,您必须在发送/接收开始运行之前调用时钟()。
祝你好运!
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <mpi.h>
#define TAG_NUMBER 777 // just something
#define DEFAULT_N 10000000 // takes ~3 seconds on my laptop
int main(int argc, char **argv)
{
int i,n,rank,size,message=0;
clock_t start = clock();
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// This test assumes two processes in MPI_COMM_WORLD
// ---------------------------------------------------------------------------
if (size != 2) {
if (rank == 0) { // only rank 0 prints
printf("Please run with exactly 2 processes.\n");
}
MPI_Finalize();
return 1;
}
// Collect from the command line the number of messages to send, default to
// DEFAULT_N.
// ---------------------------------------------------------------------------
if (rank == 0) {
if (argc > 1) {
n = atoi(argv[1]);
}
else {
n = DEFAULT_N;
}
printf("Number of messages to send = %d\n", n);
}
// Make sure everyone has the same n.
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
// ---------------------------------------------------------------------------
// Here we have ranks 1 and 2 exchange n messages via MPI_Send and MPI_Recv.
// ---------------------------------------------------------------------------
for (i=0; i<n; i++) {
if (rank == 0) {
MPI_Send(&message, 1, MPI_INT, 1, TAG_NUMBER, MPI_COMM_WORLD);
}
else{
MPI_Recv(&message, 1, MPI_INT, 0, TAG_NUMBER, MPI_COMM_WORLD, &status);
}
}
MPI_Barrier(MPI_COMM_WORLD); // not really necessary
printf("rank %d: time = %f seconds\n", rank,
(double)(clock() - start)/CLOCKS_PER_SEC);
MPI_Finalize();
return 0;
}