0

I am writing some simulation code (almost) from scratch and want to use OOP features from fortran to keep it easier to maintain. I've learned in a fortran workshop, that one should be carefull when using OOP features within performance critical parts of the code.

My naive first approach (ignoring the warning) would be the following snippet. The background is the calculation of a system energy which needs an interaction potential. For this potential, I use an abstract type (potential). All users can then add their own potentials as extensions and define a keyword that is used to allocate their potential. The energy calculation in the main program does not change.

module system_mod
implicit none

  type, abstract :: potential
  contains
    procedure(init), deferred :: init
    procedure(eval), deferred :: eval
  end type

  type, extends(potential) :: my_potential
    ! some parameters
  contains
    procedure :: init => init_my_potential 
    procedure :: eval => eval_my_potential
  end type 

  ! omitted: other extensions of 'potential'
  ! and abstract interface of potential

  type :: system
    ! some components
    class(potential), allocatable :: pair_potential
  contains
    procedure :: init ! subroutine, which is used to allocate pair_potential depending on a passed keyword
  end type

contains 

  ! implementation of all routines

end module system_mod

program main
use system_mod, only: potential, my_potential, system
implicit none

  character(len=3) :: keyword !             
  integer      :: i
  real         :: coordinates(n,3)       ! n is a huge number
  real         :: energy, system_energy
  type(system) :: test_system

  call test_system%init ( keyword ) 
  ! keyword tells which of the extensions of 'potential' is allocated

  do i = 1, n
    energy = test_system%pair_potential%eval ( ... )
    system_energy = system_energy + energy
  end do

end program

I think my main problem concerning the performance is that I don't get what the compiler actually does at compile time and which things are done at run time.

So my questions are:

  1. How or when does the compiler check, which instance of 'eval' to use?
  2. When the keyword is known at compile time, is there a type check in every iteration of the loop?
  3. Would it be better to, for example, use a procedure pointer in the main program, and associate it at the beginning to the according 'eval' procedure?

Thank you very much in advance!

4

1 回答 1

1
  1. 它有一个虚拟的过程表,可以为所有扩展类型的绑定调用,并在运行时从该表中决定。

  2. 设置关键字可能无济于事,这取决于编译器的聪明程度。如果类型在编译时已知,我会使用type而不是。class这很可能会跳过 vtable 查找。

  3. 过程指针也会影响指令流,尽管您可以保存 vtable 查找的某些部分。这实际上取决于内部结构,值得一试并进行一些性能测量。

于 2014-11-11T13:31:42.577 回答