MPI 构造数据类型之 MPI_Type_vector 实例

代码中展示了使用构造类型和不使用构造类型的例子

#include <stdio.h>
#include "mpi.h"

//不使用构造类型时 change 改为 0
#define change 1  

int main(int argc, char * argv[])
{
	int istat,myrank,nPorcs;
	float data[1024]=0;
	int tag1=99;
#if !change 
	float buff[10];
#endif 	
	
	MPI_Init(&argc,&argv);
	MPI_Status status;
	
	MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
	MPI_Comm_size(MPI_COMM_WORLD,&nPorcs);
	
	printf("This is rank %d of %d \n", myrank, nPorcs);
	
	if(0 == myrank){
		for (int i=0; i<1024; ++i){
			data[i]=i;
		}		
	}
	MPI_Barrier(MPI_COMM_WORLD);
	
	
#if change 	
	MPI_Datatype floattype;
	MPI_Type_vector(10,1,32,MPI_FLOAT,&floattype);
	MPI_Type_commit(&floattype);

	if(0 == myrank){
		MPI_Send(data,1,floattype,1,tag1,MPI_COMM_WORLD);
	}
	else{
		MPI_Recv(data,1,floattype,0,tag1,MPI_COMM_WORLD,&status);		
	} 
	
	if(1 == myrank){
		printf("use MPI_Type_vector\n");
		for(int i=0; i<10; ++i){
			printf("data[%d] = %f \n", 32*i,data[32*i]);
		}
	}
	MPI_Type_free(&floattype);
	
#else
	if(0 == myrank){
		for(int i=0; i<10; ++i){
			buff[i]=data[32*i];
		}
	}
	MPI_Barrier(MPI_COMM_WORLD);
	if(0 == myrank){
		MPI_Send(buff, 10, MPI_FLOAT, 1, tag1, MPI_COMM_WORLD);
	}
	else{
			MPI_Recv(buff, 10, MPI_FLOAT, 0, tag1, MPI_COMM_WORLD, &status);
	}	
	if(1 == myrank){
		printf("do not use MPI_Type_vector\n");
		for(int i=0; i<10; ++i){
			printf("data[%d] = %f \n", 32*i,buff[i]);
		}
	}	
#endif 	

	MPI_Finalize();
	
	return 0;
}

  

posted @ 2018-04-25 18:15  cofludy  阅读(1431)  评论(0编辑  收藏  举报