Is my implementation of a pointer swap in Fortran correct?

Viewed 354

I am trying to optimise a code that relies on a memory bandwidth intensive propagation step between two arrays. One possible optimisation is using pointers to the actual arrays and swapping them instead of swapping the arrays themselves. During the process I got a little unsure if I am doing it right.

Here is a stripped down version of what I did:

PROGRAM pointer_swap_minexample

    implicit none

    INTEGER, PARAMETER  :: I4B = SELECTED_INT_KIND(9)
    INTEGER, PARAMETER :: DP = KIND(1.0d0)
    REAL(DP), DIMENSION(:), ALLOCATABLE, TARGET :: a, b
    REAL(DP), DIMENSION(:), POINTER :: pa, pb

    INTEGER(I4B), PARAMETER :: nmax = 1000
    INTEGER(I4B), PARAMETER :: tmax = 1000
    INTEGER(I4B) :: n, t

    allocate(a(nmax), b(nmax))
    a(:) = 0.0_dp
    b(:) = 0.0_dp

    pa => a
    pb => b

    do t=1, tmax

        !=========================!
        ! heavy lifting goes here !
        !=========================!

        if(mod(t,2) .EQ. 1) then
            pa => b
            pb => a
        else
            pa => a
            pb => b
        end if

    end do

END PROGRAM pointer_swap_minexample

The actual code compiles and runs without errors. The output appears to be correct an the speedup compared to array swapping is there. Is my implementation correct in general? Are there some caveats I should be aware of? Things I should do differently?

0 Answers
Related