Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure subroutines in Fortran - Compiler optimization

Tags:

fortran

I recently discovered the use of pure functions and subroutines in Fortran. From what the Fortran manual indicates, it seems that most of my subroutines can actually be defined as pure (since I always specify the intent of all the arguments, and usually I dont have "save", "pause", or external I/O in most of my subroutines). My question is then: Should I do it? I was wondering if the compiler optimizes better pure subroutines or if it just does not matter, or if it can make things worse. Thanks !

like image 651
Tibo Avatar asked Mar 21 '12 21:03

Tibo


1 Answers

You work with the compiler to generate good code, and the more information you provide the compiler, the better a job the two of you can do together.

Whether it's labelling with intent(in) any dummy arguments you don't change, or using parameter for constants, or explicitly making pure any subprogram which doesn't have any side effects, or using forall when you don't really care about the order a loop is calculated in, by being more explicit about what you want to happen, you benefit because:

  • the compiler can now flag more errors at compile time - hey, you modified that argument you said was intent 'in', or you modified that module variable in a pure subroutine
  • your code is clearer to the next person to come to it without knowing what it's supposed to be doing (and that person could well be you three months later)
  • the compiler can be more aggressive with optimization (if the compiler has a guarantee from you that nothing is going to change, it can crankup the optimization).

Of those three benefits, the optimization is probably not the most important; in the case of pure subroutines, a smart compiler can probably see just through static analysis that your subroutine has no side effects. Still, the more guarantees you can give it, the better a job it can do of optimizing your code while maintaining correctness.

like image 77
Jonathan Dursi Avatar answered Oct 16 '22 08:10

Jonathan Dursi