How to share work roughly evenly between processes in MPI despite the array_size not being cleanly divisible by the number of processes?

前端 未结 7 1554
借酒劲吻你
借酒劲吻你 2021-01-04 10:25

Hi all, I have an array of length N, and I\'d like to divide it as best as possible between \'size\' processors. N/size has a remainder, e.g. 1000 array elements divided b

相关标签:
7条回答
  • 2021-01-04 11:14

    If I had N tasks (e.g., array elements) and size workers (e.g., MPI ranks), I would go as follows:

    int count = N / size;
    int remainder = N % size;
    int start, stop;
    
    if (rank < remainder) {
        // The first 'remainder' ranks get 'count + 1' tasks each
        start = rank * (count + 1);
        stop = start + count;
    } else {
        // The remaining 'size - remainder' ranks get 'count' task each
        start = rank * count + remainder;
        stop = start + (count - 1);
    }
    
    for (int i = start; i <= stop; ++i) { a[i] = DO_SOME_WORK(); }
    

    That is how it works:

    /*
      # ranks:                    remainder                     size - remainder
                /------------------------------------\ /-----------------------------\
         rank:      0         1             remainder-1                         size-1
               +---------+---------+-......-+---------+-------+-------+-.....-+-------+
        tasks: | count+1 | count+1 | ...... | count+1 | count | count | ..... | count |
               +---------+---------+-......-+---------+-------+-------+-.....-+-------+
                          ^       ^                            ^     ^
                          |       |                            |     |
       task #:  rank * (count+1)  |        rank * count + remainder  |
                                  |                                  |
       task #:  rank * (count+1) + count   rank * count + remainder + count - 1
    
                \------------------------------------/ 
      # tasks:       remainder * count + remainder
    */
    
    0 讨论(0)
提交回复
热议问题