Search code examples
if-statementoptimizationfortranfortran77

Optimizing if-then-else statement in Fortran 77


For my C++ code, I asked this question about two days ago. But I realize now that I have to do the coding in Fortran since the kernels I write is going to be part of an existing application written in Fortran 77. Therefore I am posting this question again, this time the context is Fortran. Thank you.

I have different functions for square matrix multiplication depending on matrix size which varies from 8x8 through 20x20. The functions differ from each other because each employ different strategies for optimization, namely, different loop permutations and different loop unroll factors. Matrix size is invariant during the life of a program, and is known at compile time. My goal is to reduce the time to decide which function must be used. For example, a naive implementation is:

if (matrixSize == 8) C = mxm8(A, B);
else if (matrixSize == 9) C = mxm9(A,B);
 ...
else if (matrixSize == 20) C = mxm20(A,B);

The time taken to decide which function to use for every matrix multiplication is non-trivial in this case, specially since matrix multiplication happens frequently in the code. Thanks in advance for any suggestion on how to handle this in Fortran 77.


Solution

  • If matrixSize is a compile time constant in a language sense (i.e. it is a Fortran PARAMETER), then I would expect most optimising compilers to take advantage of that, and completely eliminate a runtime branch.

    If matrixSize is not a compile time constant, then you should make it one. Facilities provided in later Fortran language revisions (modules) make it very easy to propagate such a runtime constant from a single point of definition to a point of use.

    Note that conforming Fortran 77 is also conforming Fortran 90, and with very few exceptions, will also be conforming Fortran 2015.