结构体类型的创建(AOS&SOA组合)
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#define DOUBLE_NUMS 2
struct Value{
int a;
double b[ DOUBLE_NUMS] ;
} ;
void initArray ( struct Value * array, int size, int bSize)
{
for ( int i = 0 ; i < size; i++ )
{
array[ i] . a = ( int ) ( rand ( ) % 10 + 1 ) ;
for ( int j = 0 ; j < bSize; j++ ) array[ i] . b[ j] = ( double ) ( rand ( ) % 10 + 1 ) ;
}
}
void printArray ( const char * name, struct Value * array, int ranknode, int size, int bSize)
{
printf ( "%s rank%d\n" , name, ranknode) ;
for ( int i = 0 ; i < size; i++ )
{
printf ( "i=%d a=%d" , i, array[ i] . a, array[ i] . b) ;
for ( int j = 0 ; j < bSize; j++ ) printf ( " b[%d]=%lf" , j, array[ i] . b[ j] ) ;
printf ( "\n" ) ;
}
printf ( "\n" ) ;
}
int main ( int argc, char * argv[ ] )
{
int structSize= 2 ;
int rank;
MPI_Init ( & argc, & argv) ;
MPI_Comm_rank ( MPI_COMM_WORLD, & rank) ;
MPI_Datatype mystruct;
int blocklens[ 2 ] ;
MPI_Aint indices[ 2 ] ;
MPI_Datatype old_types[ 2 ] ;
struct Value value;
blocklens[ 0 ] = 1 ;
blocklens[ 1 ] = 2 ;
old_types[ 0 ] = MPI_INT;
old_types[ 1 ] = MPI_DOUBLE;
MPI_Get_address ( & value. a, & indices[ 0 ] ) ;
MPI_Get_address ( & value. b, & indices[ 1 ] ) ;
indices[ 1 ] = indices[ 1 ] - indices[ 0 ] ;
indices[ 0 ] = 0 ;
MPI_Type_create_struct ( 2 , blocklens, indices, old_types, & mystruct) ;
MPI_Type_commit ( & mystruct) ;
MPI_Aint lb, extent;
MPI_Type_get_extent ( mystruct, & lb, & extent) ;
int size;
MPI_Type_size ( mystruct, & size) ;
struct Value * pt = ( struct Value * ) malloc ( structSize * sizeof ( struct Value) ) ;
if ( 0 == rank) {
printf ( "double stride: %d\n" , ( int ) indices[ 1 ] ) ;
printf ( "MPI_Type_get_extent length:%d\n" , ( int ) extent) ;
printf ( "MPI_Type_get_extent min: %d\n" , ( int ) lb) ;
printf ( "size of struct: %d\n" , ( int ) sizeof ( value) ) ;
printf ( "MPI_Type_size: %d\n" , size) ;
initArray ( pt, structSize, DOUBLE_NUMS) ;
printf ( "\nrank0 打印 " ) ;
printArray ( "struct" , pt, rank, structSize, DOUBLE_NUMS) ;
}
MPI_Bcast ( pt, structSize, mystruct, 0 , MPI_COMM_WORLD) ;
printArray ( "struct" , pt, rank, structSize, DOUBLE_NUMS) ;
MPI_Type_free ( & mystruct) ;
free ( pt) ;
MPI_Finalize ( ) ;
}