Fortran: initializing of and assigning value to arrays

Developer picture Developer · Jan 12, 2012 · Viewed 27.8k times · Source

To initialize and assign value to arrays in Fortran we do as the following:

Initializing:

real(kind=8):: r(3,4)
...
r(:,:) = 0.0_8

what if we use only

real(kind=8):: r(3,4)
...
r = 0.0_8

and what if we do as:

real(kind=8):: r(3,4)
...
r = 0

also for situation such as:

real(kind=8):: r(3,4), q(3,4), p(30,40)
...
q = 0
r = q
r = p(1:3,21:24)

we prefer to do as:

real(kind=8):: r(3,4), q(3,4), p(30,40)
...
q = 0.0_8
r(:,:) = q(:,:)
r(:,:) = p(1:3,21:24)

we are not sure so hope you provide us some reasons for each one you prefer.

Answer

max picture max · Jan 13, 2012

For general considerations (including declaration and assignation) about efficiently using arrays in Fortran, I would suggest to read this.

For more precise answer to your question, I did some tests some months ago that may interest you. Here are the results. This is a test on my personnal laptop on Linux Archlinux x86-64, with GNU Fortran (GCC) 4.6.1 20110819 (prerelease) without optimization options.

do i = 1 , 100
  do j = 1 , 100
    do k = 1 , 100 ! innest is fastest
      array ( i , j , k ) = 0.0d0
    end do
  end do
end do
! reference time : 1.00

to

do i = 1 , 100
  do j = 1 , 100
    do k = 1 , 100
      array ( k , j , i ) = 0.0d0
    end do
  end do
end do
! time : 0.499

to

array = 0.0d0
! time : 0.250

to

array ( : , : , : ) = 0.0d0
! time : 0.250