以下は、あなたが求めていることを行う完全なプログラムです。元のバージョンの動作を妨げるいくつかの問題がありました:
- タグが一致しませんでした。これにより、プログラムが停止する可能性があります。
- MPI_COMM_WORLD に正確に 2 つの MPI プロセスが含まれているかどうかはチェックされません。これもストールの原因となります。
- コマンド ラインに引数が存在しない場合、seg fault が発生する可能性があります。のデフォルト値を追加しました
n
。
- タイミングは有用なものを生成しません。send/recv が実行を開始する前に clock() を呼び出す必要があります。
幸運を!
#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;
}