program main !*****************************************************************************80 ! !! PRIME computes the sum of the prime numbers between 2 and 100,000. ! ! Discussion: ! ! This program uses MPI to divide the work among P processes. ! ! Each process prints out its partial result and wall clock time. ! ! Process 0 prints the total and total time. ! use mpi integer i integer id integer id_n_hi integer id_n_lo double precision id_time integer id_total integer ierr integer j integer :: n_hi = 100000 integer :: n_lo = 2 integer p logical prime double precision wtime double precision wtime_total double precision wtime1 double precision wtime2 integer total ! ! Initialize MPI. ! call MPI_Init ( ierr ) ! ! Get this process's ID. ! call MPI_Comm_rank ( MPI_COMM_WORLD, id, ierr ) ! ! Find out how many processes are available. ! call MPI_Comm_size ( MPI_COMM_WORLD, p, ierr ) ! ! Work that only process 0 should do. ! if ( id == 0 ) then write ( *, '(a)' ) ' ' write ( *, '(a)' ) 'PRIME' write ( *, '(a)' ) ' FORTRAN90 version' write ( *, '(a,i8)' ) ' Number of processes = ', p write ( *, '(a)' ) ' ' write ( *, '(a)' ) ' ID N_LO N_HI TOTAL TIME' write ( *, '(a)' ) ' ' end if ! ! Each process computes a portion of the sum. ! id_total = 0 id_time = 0.0 id_n_lo = ( ( p - id ) * n_lo & + ( id ) * ( n_hi + 1 ) ) & / ( p ) id_n_hi = ( ( p - id - 1 ) * n_lo & + ( id + 1 ) * ( n_hi + 1 ) ) & / ( p ) - 1 ! ! Begin the work done by one "process" ! wtime1 = MPI_Wtime ( ) do i = id_n_lo, id_n_hi prime = .true. do j = 2, i - 1 if ( mod ( i, j ) == 0 ) then prime = .false. exit end if end do if ( prime ) then id_total = id_total + i end if end do wtime2 = MPI_Wtime ( ) wtime = wtime2 - wtime1 write ( *, '(2x,i8,2x,i8,2x,i8,2x,i12,2x,g14.6)' ) & id, id_n_lo, id_n_hi, id_total, wtime ! ! Use REDUCE to gather up the partial totals and send to process 0. ! Use REDUCE to gather up the WALL CLOCK times and send to process 0. ! call MPI_Reduce ( id_total, total, 1, MPI_INTEGER, MPI_SUM, 0, MPI_COMM_WORLD, ierr ) call MPI_Reduce ( wtime, wtime_total, 1, MPI_DOUBLE_PRECISION, MPI_SUM, 0, MPI_COMM_WORLD, ierr ) if ( id == 0 ) then write ( *, '(a)' ) ' ' write ( *, '(2x,a8,2x,i8,2x,i8,2x,i12,2x,g14.6)' ) & ' Total', n_lo, n_hi, total, wtime_total end if call MPI_Finalize ( ierr ) stop end