Search code examples
fortraninline

Inlining functions in Fortran


In a Fortran project we use a binary search to find a desired value:

integer function binsearch(tab, el)
  implicit none

  real, intent(in) :: tab(:), el
  integer :: a, b, mid

  a = 1
  b = size(tab)

  do while (b - a > 1)
    mid = (a + b)/2
    if (el >= tab(mid)) then
      a = mid
    else
      b = mid
    endif
    ! if (el < tab(mid + 1)) exit ! BAD OPTIMIZATION !
  enddo

  binsearch = a
end function binsearch

Later on we simply use it

foo = binsearch(tab, el)

Unfortunately the surrounding routine is used so heavily, that the BAD OPTIMIZATION raises the total execution time by a half. So I considered inlining the function to diminish the call cost.

Is it possible to anyhow mark this function for inlining? In C there's the keyword inline which is a suggestion for the compiler - and is there anything like this in Fortran 2008?

I don't want to copy-paste this for the sake of the code clarity.


Solution

  • It depends on the compiler. I can verify that this works for Cray and Intel Fortran compilers, but the statements are slightly different.

    Cray compiler:

    !dir$ forceinline :: frob
    

    This would force the compiler to inline function frob. You'd place this immediately above the function definition.

    Intel compiler:

    !dir$ attributes forceinline :: frob
    

    I do not see that gcc/gfortran currently has these options.

    Manuals on both compilers cover this.