2
  MODULE fractions
  real*8, parameter:: one_over_three = 1.d0/3.d0
  real*8, parameter:: eleven_over_eighteen = 11.d0/18.d0
  real*8, parameter:: five_over_64 = 5.d0/64.d0
  real*8, parameter:: five_over_eight = 5.d0/8.d0
  real*8, parameter:: five_over_sixteen = 5.d0/16.d0
  real*8, parameter:: fiveteen_over_eight = 15.d0/8.d0
  real*8, parameter:: fiveteen_over_four = 15.d0/4.d0
  real*8, parameter:: fiveteen_over_two = 15.d0/2.d0
  real*8, parameter:: fortyfive_over_eight = 45.d0/8.d0
  real*8, parameter:: nine_over_two = 9.d0/2.d0
  real*8, parameter:: one_over_eight = 1.d0/8.d0
  real*8, parameter:: three_over_eight = 3.d0/8.d0
  real*8, parameter:: three_over_two = 3.d0/2.d0
  real*8, parameter:: two_over_three = 2.d0/3.d0
  real*8, parameter:: eight_over_three = 8.d0/3.d0
  real*8, parameter:: seven_over_two = 7.d0/2.d0
  END MODULE fractions

In my fortran program, I have to call the same subroutine many times. It involves a couple of fractions. Does it increase the performance of the subroutine if I use a module as above or has the program to perform the calculation of the fractions whenever the subroutine is called and uses the module?

stegmaja
  • 63
  • 2
  • 1
    Irrelevant comment: native English writers would have `fifteen` where you have `fiveteen`. – High Performance Mark Jun 03 '20 at 16:11
  • 1
    relevant comment: modern Fortran users would write `use iso_fortran_env`, and convert `REAL*8` into `REAL(kind=REAL64)` (See https://stackoverflow.com/questions/3170239/fortran-integer4-vs-integer4-vs-integerkind-4) – kvantour Jun 04 '20 at 11:57

1 Answers1

5

In optimizing compilers it does not matter. These fractions will be per-computed wherever they appear. The performance should be the same no matter whether you write three_over_two or 3.d0/2.d0 or say 3/2d0 directly.

Personally I would not bother with such a module, it obscures readability. That is individual and a local constant may often be good for readability. But I would keep it local (not in a dedicated module for constants) and I would name the constant according to its purpose, not according to its value.

The comments show a potential issue where a pair of parentheses may be necessary, namely x*3./2. actually meaning (x*3.)/2.. I personally tend to place these factors at the start of an expression so it is less of an issue but it is good to take that into account.

  • Better `(3/2d0)`, probably. – francescalus Jun 03 '20 at 13:33
  • Depends on the context, of course. I assumed proper parentheses where necessary. – Vladimir F Героям слава Jun 03 '20 at 13:35
  • 2
    Parentheses may be necessary for the compiler to actually pre-compute 3/2. - consider `x*3./2.` where `x` is variable. The expression as written is actually `(x*3.)/2.`, which can be slightly different than `x*(3./2.)`. So a pedantic compiler (no `ffast-math` and similar) would not precompute anything in the expression with parenthesis. – Ross Jun 04 '20 at 16:21