【问题标题】:Type bound procedures of polymorphic components of derived types派生类型的多态组件的类型绑定过程
【发布时间】:2014-11-11 13:17:59
【问题描述】:

我正在从头开始(几乎)编写一些模拟代码,并希望使用 fortran 的 OOP 功能使其更易于维护。我在一个 fortran 研讨会上了解到,在代码的性能关键部分中使用 OOP 功能时应该小心。

我天真的第一种方法(忽略警告)将是以下 sn-p。背景是计算需要相互作用势的系统能量。对于这种潜力,我使用抽象类型(潜力)。然后,所有用户都可以添加他们自己的潜力作为扩展,并定义一个关键字来分配他们的潜力。主程序中的能量计算没有改变。

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

我认为我关于性能的主要问题是我不知道编译器在编译时实际做了什么以及在运行时做了哪些事情。

所以我的问题是:

  1. 编译器如何或何时检查使用哪个“eval”实例?
  2. 当关键字在编译时已知时,是否在循环的每次迭代中进行类型检查?
  3. 例如,在主程序中使用过程指针并在开头将其与相应的“eval”过程相关联会更好吗?

非常感谢您!

【问题讨论】:

    标签: fortran fortran2003


    【解决方案1】:
    1. 它有一个virtual table 过程,可以为所有扩展类型的绑定调用这些过程,并在运行时根据该表决定。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多