Search code examples
optimizationfortranlapackblas

Optimization of conditional Fortran loop


I would like to optimize for speed the following block of code:

DO i=1, dim1
  DO j=1, dim2
    DO k=1, dim3
      IF (A(k,j,i)>0) &
        B(k,j,i) = exp(C(k))/A(k,j,i)
    ENDDO
  ENDDO
ENDDO

Very importantly, A is an INTEGER and B and C are COMPLEX!

There are two issues: 1) How to replace this by a BLAS/LAPACK call? The issue is the condition. 2) Calculation of the exp is slow. How to speed that up?


Solution

  • I ran a couple of tests with idim[1-3] being various permutation of [40,40,1000] and found that using a temporary array for the exponential and keeping the original loop ordering to be fastest by a factor of 2 or more than the other answer supplied. You milage may vary with compiler etc.

    d=exp(c)
    DO i=1, dim1
      DO j=1, dim2
        DO k=1, dim3
          IF (A(k,j,i)>0) &
            B(k,j,i) = d(k)/A(k,j,i)
        ENDDO
      ENDDO
    ENDDO