在Fortran 90子例程中重复使用2D数组
我有一个Fortran 90程序,其结构如下所示。在在Fortran 90子例程中重复使用2D数组,fortran,fortran90,Fortran,Fortran90,我有一个Fortran 90程序,其结构如下所示。在子例程A中计算2D数组myMatrix(1:N,1:N)的步骤非常昂贵。它只取决于全局变量N,只需计算一次;子程序中的“其他步骤”不会更改myMatrix的值。目前,无论何时调用子程序,都将计算myMatrix 有没有一种方法可以让2D数组myMatrix只计算一次 module constants integer :: N end module constans module A_module use constants conta
子例程A
中计算2D数组myMatrix(1:N,1:N)的步骤非常昂贵。它只取决于全局变量N
,只需计算一次;子程序中的“其他步骤”不会更改myMatrix的值。目前,无论何时调用子程序,都将计算myMatrix
有没有一种方法可以让2D数组myMatrix
只计算一次
module constants
integer :: N
end module constans
module A_module
use constants
contains
subroutine A
! compute the 2D real array myMatrix(1:N,1:N)
! other steps that use myMatrix
end subroutine A
end module A_module
program main
use constants
use A_module
integer :: k
do k = 1,10000
call A
end do
end program main
当然。确定在do循环外部初始化矩阵的
init_a_matrix
子例程
subroutine init_a_matrix
! Do initialization here
end subroutine init_a_matrix
那你有
call init_a_matrix
do k = 1,10000
call A
end do
如果要消除子例程A中
myMatrix
的冗余初始化(因为它只需要在子例程初始调用时计算一次),可以使用SAVE
属性和逻辑
标志。在子程序A
中
logical :: init_flag = .false.
real, save :: matrix_a(n,n)
if (init_flag .eqv. .false.) then
! Initialize matrix_a on the first call to the subroutine and reset init_flag.
init_flag = .true.
end if
如果
myMatrix
是子例程A
的一个未保存的局部变量,则有必要在子例程的每个条目上重新计算其值:当子例程完成执行时,未保存的局部变量变得未定义
但是,有许多方法可以重用该变量:
- 使其成为保存的局部变量:保存的局部变量保留其定义
- 将其作为伪参数,而不是局部变量(参数关联):其定义来自调用者
- 把它当作其他形式的非局部变量(other):它的定义来自另一个地方
subroutine A
<declaration>, save :: mymatrix
logical, save :: first_entry = .TRUE.
if (first_entry) then
! set up mymatrix
first_entry = .FALSE.
end if
! ...
end subroutine A
或者可以将变量作为伪参数:
mymatrix_actual = ...
do k = 1,10000
call A(mymatrix_actual) ! A now has the dummy variable
end do
mymatrix_actual = ...
do k = 1,10000
call A(mymatrix_actual) ! A now has the dummy variable
end do