【发布时间】: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
我认为我关于性能的主要问题是我不知道编译器在编译时实际做了什么以及在运行时做了哪些事情。
所以我的问题是:
- 编译器如何或何时检查使用哪个“eval”实例?
- 当关键字在编译时已知时,是否在循环的每次迭代中进行类型检查?
- 例如,在主程序中使用过程指针并在开头将其与相应的“eval”过程相关联会更好吗?
非常感谢您!
【问题讨论】:
标签: fortran fortran2003