You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求Fortran中新增尺寸为1的三维维度影响性能的示例

合并二维与三维Fortran程序的性能验证与场景探索

Veryreverie提出一种合并二维和三维Fortran程序的方案:仅保留三维程序,在二维场景中将第三维度设为1。我原本未考虑该方案,认为新增无用的第三维度会带来性能开销。

随后我开展了大量测试,对比二维程序与第三维度设为1的三维程序的性能,测试代码如下:

module m
  implicit none
  
  type :: int_3dim_t
    integer :: x
    integer :: y
    integer :: z
  end type int_3dim_t
  
end module m

program main
  use m
  implicit none
  
  type(int_3dim_t) :: ii_curr, full_dim
  real, dimension(:,:,:,:), allocatable :: myMatrix
  real :: aaa
  integer :: ll
  
  open(unit=50,file='dim2.dat',status='old')
  read(50,*) full_dim%x,full_dim%y
  close(50)
  full_dim%z = 1
  allocate(myMatrix(1:8,1:full_dim%x,1:full_dim%y,1:full_dim%z))
    
  associate (ii_x => ii_curr%x, ii_y => ii_curr%y, ii_z => ii_curr%z)
  do ii_z = 1, full_dim%z
    do ii_y = 1, full_dim%y
      do ii_x = 1, full_dim%x
        do ll=1,8
          myMatrix(ll,ii_curr%x,ii_curr%y,ii_curr%z) = myMatrix(ll,ii_curr%x,ii_curr%y,ii_curr%z) + my_calc(ii_curr,ll)
        enddo
      enddo
    enddo
  enddo
  end associate
  
  print *,myMatrix(:,10,10,1)
  
contains

  real function my_calc(ii,ll)
    type(int_3dim_t), intent(in) :: ii
    integer, intent(in) :: ll
    
    my_calc = sqrt(real((ii%x/100.0)**2+(ii%y/100.0)**2))*ll
    
  end function my_calc
    
end program main

测试输入文件内容为10000 10000(其他数值不影响结论),使用gfortran 12.1.1编译器并开启-O2优化选项(二维版本移除所有与第三维度相关的代码)。

令人惊讶的是,二者执行时间无差异。因此我寻求符合正确Fortran循环顺序(内层循环为第一个索引,外层循环为最后一个索引)的简单示例,以展示第三维度设为1时会对执行时间产生影响的场景。

内容的提问来源于stack exchange,提问作者Stef1611

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:48:58