我注意到关于派生数据类型的内存使用存在奇怪的行为。以下Fortran90代码演示了这个问题。
module prec
implicit none
integer, parameter :: d_t = selected_real_kind(15,307)
end module
module typdef
use prec
implicit none
type level_2
real(kind=d_t), allocatable :: lev_3(:)
end type
type level_1
type(level_2),allocatable :: lev_2(:,:)
end type
type array
type(level_1),allocatable :: lev_1(:,:)
end type
end module
program mem_test
use prec
use typdef
implicit none
integer :: n,i,j,k,l,m,egmax,niter,ncells,namom,nsmom
real(kind=d_t),allocatable :: simple_array(:,:,:,:,:)
type(array) :: fancy_array
real(kind=d_t) :: it
egmax=7
niter=2
ncells=3000000
namom=1
nsmom=1
!
!
!
allocate( simple_array(egmax,niter,ncells,namom,nsmom) )
!
!
!
allocate( fancy_array%lev_1(egmax,niter))
do i=1,niter
do j=1,egmax
allocate( fancy_array%lev_1(j,i)%lev_2(ncells,namom) )
end do
end do
do i=1,niter
do j=1,egmax
do k=1,namom
do l=1,ncells
allocate( fancy_array%lev_1(j,i)%lev_2(l,k)%lev_3(nsmom) )
end do
end do
end do
end do
!
do n=1,100000
it=0.0_d_T
do i=1,100000
it=it+1.0_d_t
end do
end do
!
!
deallocate(simple_array)
deallocate(fancy_array%lev_1)
end program
我想将数据存储在多维数组中(例如max*niter*ncell*namom*nsmom双精度数字)。我有两种不同的方法:
- 一个多维标准数组“simple_array(egmax,niter,...,)”
- 一个嵌套的派生数据结构“fancy_array”,如我所提供的代码中定义的那样。
我使用以下编译代码:
ifort -g -o test.exe file.f90
我在valgrind中运行了它,并比较了simple_array和fancy_array的内存消耗。与预期一样,simple_array使用了大约300MB,而fancy_array使用了3GB(是其10倍),尽管它们都存储了相同数量的实数。因此,它应该只消耗300MB。
运行一个更简单的测试用例,其中派生类型仅有一层,例如:
type level_1
real(kind=d_t),allocatable :: subarray(:)
end type
type array
type(level_1),allocatable :: lev_1(:)
end type
消耗的内存与我预期的完全一致,不会消耗10倍的内存。有人观察到类似的行为或者有任何线索可以解释这种情况吗?我唯一能想到的原因是fancy_array分配了非连续的内存,而fortran需要跟踪它,因此导致内存消耗增加。如果您有任何意见或类似的观察结果,请不吝赐教。
感谢您的帮助。
Sebastian