#include #include #include #include #include #define TIMES 40000000 float randx(void) { float v; srand((unsigned int)time(NULL)); v = (float)rand()/(float)(RAND_MAX); return v; } int main(void) { int comm_sz, my_rank; int i, local_n, local_t, global_t = 0; MPI_Init(NULL, NULL); /* Since there is a constant defining how many times the cycle has to be executed in total, it would not be necessary to have the rank 0 process bradcasting the number of iterations to be executed by each process. */ MPI_Comm_size(MPI_COMM_WORLD, &comm_sz); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); local_n = TIMES / comm_sz; // static distribution of work, // knowing that the remain of the division is zero. local_t = 0; for( i = 0; i < local_n; i++ ){ double x, y; x = randx( ); /*randx return a random real number between 0 and 1*/ y = randx( ); if( x*x+y*y<=1.0) local_t = local_t + 1; } /* char processor_name[MPI_MAX_PROCESSOR_NAME]; int name_len; MPI_Get_processor_name(processor_name, &name_len); printf("Processor %s, rank %d" " out of %d processors, local_t:%d\n", processor_name, my_rank, comm_sz, local_t); */ MPI_Reduce(&local_t, &global_t, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if(my_rank == 0) { double pi; pi = 4.0*((double)global_t/(double)TIMES); //printf("global_t:%d pi:%f\n", global_t, pi); printf("pi:%f\n", pi); } MPI_Finalize(); return 0; }