Fortran

Guide To Learn

Exercise 1: Finding the array subranges on each image

We need a function that returns a start and end index for each image, given the integer size of the global array to be decomposed. For example, for an input 100 and total number of images 2, the result should be [1, 50] on image 1 and [51, 100] on image 2. When the input is divisible by num_images(), the solution is straightforward. However, we also need to handle a special case when the input isn’t divisible by num_images(); for example, if input is 100 and num_images() == 3. The following listing provides the solution.

Listing 7.8 Calculating start and end indices on each image

pure function tile_indices(dims)
 
  integer, intent(in) :: dims                                ❶
  integer :: tile_indices(2)                                 ❷
  integer :: offset, tile_size
 
  tile_size = dims / num_images()                            ❸
 
  tile_indices(1) = (this_image() - 1) * tile_size + 1       ❹
  tile_indices(2) = tile_indices(1) + tile_size - 1          ❺
  offset = num_images() - mod(dims, num_images())            ❻
  if (this_image() > offset) then                            ❻
    tile_indices(1) = tile_indices(1) &                      ❻
                    + this_image() - offset - 1              ❻
    tile_indices(2) = tile_indices(2) &                      ❻
                    + this_image() - offset                  ❻
  end if                                                     ❻
 
end function tile_indices

❶ Input integer scalar, size of array to decompose

❷ Array to store the result in

❸ First guess for tile size; correct only if dims is divisible by num_images()

❹ First guess for start index

❺ First guess for end index

❻ If dims is not divisible by num_images(), distribute the remainder accordingly.

This function is also an important piece of the parallel tsunami simulator and is available there as a function in src/ch07/mod_parallel.f 90.

Exercise 1: Finding the array subranges on each image

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top