Search code examples
if-statementfortrangfortrando-loops

Avoid IF statements in a Fortran DO loops


In my Fortran program I have something similar to this do loop

do i = 1,imax
    if(period) then
        call g_period()
    else
        call g()
    endif
 enddo

I have this several places and sometimes several If loops within a do loop which checks whether I should call function X or Y. What is common for all this is that period is defined in the input file, and it is unchanged during the whole run time. Is there a way to avoid the if statements - because my speed is killed by all the checking stuff? Although, I want to maintain the generic why of being able to run the program one time with period = true and other times with period=false.


Solution

  • If the speed is really crucial you can always write two different versions. One for true and one for false:

    if(period) then
      do i = 1,imax
        call g_period()
      end do
    else
      do i = 1,imax
        call g()
      end do
    end if
    

    You can have even completely separate subroutine and everything.

    When you call subroutines, g() and the alternative, that do serious work, it is likely that there won't be too much performance penalty for the if. However, if you do stuff like looping over a large 3D array of many points and do some mathematical operation in every point, with just a few exeptions, it may even be faster to to compute it everywhere and undo it for those few exceptional points afterwards, rather than introduce a brench into the tight loop.