我经常遇到的问题是,将大型数组及其子集作为参数传递或使用模块是否更好。例如:
type( plant_type ), dimension( 5, 50000 ) :: plant
请注意,一个维度很长,另一个维度更小。 传递的参数只是数组的一个子集:
call plantgrowth( plant(:,icell) )
我可以通过添加
来调用plantgrowth()
而不是传递这个参数,而不是传递这个参数
use md_biosphere, only: plant
在子程序plantgrowth()
内。
==>哪个选项更快?
以下是另一个Fortran示例:
使用参数:
module md_biosphere
implicit none
private
public :: biosphere, plant_type ! only plant_type (not plant) is made public, but not instance of the type ('plant')
! the important aspect here is that ncells >> nplant
integer, parameter :: ncells = 500000
integer, parameter :: nplant = 50
type plant_type
real :: foliage
real :: roots
real :: wood
end type plant_type
type( plant_type ), dimension( nplant, ncells ) :: plant
contains
subroutine biosphere()
integer :: icell
do icell=1,ncells
call plantgrowth( plant(:,icell) )
end do
end subroutine biosphere
subroutine plantgrowth( plant )
type( plant_type ), dimension(nplant), intent(inout) :: plant
integer :: iplant
! more stuff here ...
do iplant=1,nplant
plant(iplant)%foliage = 1.0
plant(iplant)%roots = 1.0
plant(iplant)%wood = 1.0
end do
end subroutine plantgrowth
end module md_biosphere
!//////////////////////////////////////////////////////////
program example_module
use md_biosphere, only: biosphere
implicit none
call biosphere()
end program example_module
使用“使用模块”:
module md_biosphere
implicit none
private
public :: biosphere, plant ! instance 'plant' is made public and does not have to be passed as argument
! the important aspect here is that ncells >> nplant
integer, parameter :: ncells = 500000
integer, parameter :: nplant = 50
type plant_type
real :: foliage
real :: roots
real :: wood
end type plant_type
type( plant_type ), dimension( nplant, ncells ) :: plant
contains
subroutine biosphere()
integer :: icell
do icell=1,ncells
! no arguments are passed
call plantgrowth( icell )
end do
end subroutine biosphere
subroutine plantgrowth( icell )
integer, intent(in) :: icell
integer :: iplant
! more stuff here ...
do iplant=1,nplant
plant(iplant,icell)%foliage = 1.0
plant(iplant,icell)%roots = 1.0
plant(iplant,icell)%wood = 1.0
end do
end subroutine plantgrowth
end module md_biosphere
!//////////////////////////////////////////////////////////
program example_module
use md_biosphere, only: biosphere
implicit none
call biosphere()
end program example_module