2011-05-24 21 views
1

在我的並行編程書中,我遇到了這個代碼,說奴隸生成的數據集,但是,我認爲主人acutally生成的數據集。並行處理 - 從站是否生成數據集?

這條線特別是爲什麼我相信主人生成數據集。

for (i=0; i < ARRAY_SIZE; i++) 
     numbers[i] = i; 

有人可以確認主或奴隸生成的數據集?

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

#define TRIALS 20 
#define ARRAY_SIZE 1000000 

int main(int argc, char *argv[]) 
{ 
    int myid, numprocs; 
    double startwtime, endwtime; 
    int namelen; 
    int* numbers = new int[ARRAY_SIZE]; 
    int i, j, sum, part_sum; 
    int s, s0, startIndex, endIndex; 
    double totalTime; 

    char processor_name[MPI_MAX_PROCESSOR_NAME]; 

    MPI_Init(&argc,&argv); 
    MPI_Comm_size(MPI_COMM_WORLD,&numprocs); 
    MPI_Comm_rank(MPI_COMM_WORLD,&myid); 
    MPI_Get_processor_name(processor_name,&namelen); 

    fprintf(stderr,"Process %d on %s\n", myid, processor_name); 
    fflush(stderr); 

    for (i=0; i < ARRAY_SIZE; i++) 
     numbers[i] = i; 

    if (myid == 0) 
    { 
     s = (int) floor(ARRAY_SIZE/numprocs); 
     s0 = s + ARRAY_SIZE%numprocs; 
     //printf("s=%d , s0= %d\n", s, s0); 
    } 

    MPI_Bcast(&s, 1, MPI_INT, 0, MPI_COMM_WORLD); 
    MPI_Bcast(&s0, 1, MPI_INT, 0, MPI_COMM_WORLD); 

    startIndex = s0 + (myid - 1)*s; 
    endIndex = startIndex + s; 

    totalTime = 0; 

    for (j = 1; j <= TRIALS; j++) 
    { 
     if (myid == 0) 
     { 
      startwtime = MPI_Wtime(); 
     } 

     sum = 0; 
     part_sum = 0; 

     if (myid == 0) // master 
     { 
      // compute sum of master's numbers 
      for (i = 0; i < s0; i++) 
      { 
       part_sum += numbers[i]; 
      } 
     } 
     else 
     { 
      for (i = startIndex; i < endIndex; i++) 
      { 
       part_sum += numbers[i]; 
      } 
     } 
     MPI_Reduce(&part_sum, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); 
     if (myid == 0) 
     { 
      double runTime; 
      endwtime = MPI_Wtime(); 
      runTime = endwtime - startwtime; 

      printf("Trial %d : Execution time (sec) = %f\n", j, runTime); 
      printf("Sum = %d \n", sum); 
      totalTime += runTime; 
     } 
    } // end for 
    if (myid == 0) 
     printf("Average time for %d trials = %f", TRIALS, totalTime/TRIALS); 

    MPI_Finalize(); 
} 

回答

2

兩個主從站產生的整個陣列。您必須記住,您的程序在所有節點上運行,並且相關代碼的一部分不區分主/從。所以你的書的措辭沒有錯,但可以澄清。 :)

+0

是因爲MPI_Init嗎? – Raptrex 2011-05-24 05:08:41

+0

實質上,是的。只有在MPI_Init成功返回後,MPI進程才能保證啓動並擁有參數列表的副本。 – 2011-05-24 05:10:43