Is Dynamically allocated array having the same reading and writing speed as normal array for Fortran?

Viewed 115

I am working with fortran 90, my program depends heavily on accessing different elements of array. So I wonder if reading and writing speed of dynamically allocated array are the same as normal array.

1 Answers

I have written a small test program. It accesses an array at random positions and calculates the sum of the elements at these positions. This is done for a normal and a dynamically allocated array. Both arrays contain the same data and are accessed at the same points.

With gfortran and ifort I could not find a significant difference for any size of the arrays.

Here is the code I used. You can adjust the variables arr_size and num_loop to adjust the size of the arrays/ number of runs used for averaging the times. The current parameters (array size = 10 million, 10 averaging runs) have the following runtimes:

Average elapsed time classical array: 0.060910000280 seconds

Average elapsed time dynamically allocated array: 0.060630000010 seconds

Difference in the sum between first and second sum: 0.00000E+00

program alloc_test
  implicit none
  ! determines the size of the arrays.
  integer, parameter :: arr_size = 1e7
  ! sets the number of averaging runs
  integer :: num_loop = 10
  integer, dimension(arr_size) :: access
  ! pre allocated array
  real*8, dimension(arr_size) :: arr1
  ! dinamically allocated array.
  real*8, dimension(:), allocatable :: arr2
  integer :: t1, t2, clockrate, i, j
  real*8 :: temp, tot_time, sum1, sum2
  integer :: r_size
  integer, dimension(:), allocatable :: rseed
  !get random seed so the second test uses the same random numbers.
  call random_seed(size = r_size)
  allocate(rseed(r_size))
  call random_seed(get = rseed)
  call system_clock(count_rate = clockrate)
  tot_time = 0
  temp = 0
  do j = 1, num_loop, 1
    call random_number(arr1)
    access = floor(arr1 *arr_size) + 1
    call system_clock(t1)
    do i = 1, arr_size, 1
      temp = temp + arr1(access(i))
    end do
    call system_clock(t2)
    tot_time = tot_time + (t2-t1) /(1.0 * clockrate)
  end do
  sum1 = temp
  write(*,"(a,x,f15.12,x,a)") "Average elapsed time classical array:", tot_time/num_loop, "seconds"

  ! reset random seed:
  call random_seed(put = rseed)
  allocate(arr2(arr_size))
  tot_time = 0
  temp = 0
  do j = 1, num_loop, 1
    call random_number(arr2)
    access = floor(arr2 *arr_size) + 1
    call system_clock(t1)
    do i = 1, arr_size, 1
      temp = temp + arr2(access(i))
    end do
    call system_clock(t2)
    tot_time = tot_time + (t2-t1) /(1.0 * clockrate)
  end do
  write(*,"(a,x,f15.12,x,a)") "Average elapsed time dynamically allocated array:", tot_time/num_loop, "seconds"
  sum2 = temp
  write(*, "(a, e12.5)") "Difference in the sum between first and second sum: ", sum1 - sum2
end program alloc_test
Related