fortran - 动态分配的数组与 Fortran 的普通数组具有相同的读写速度吗?

标签 fortran

我正在使用 Fortran 90,我的程序很大程度上依赖于访问数组的不同元素。所以我想知道动态分配数组的读写速度是否与普通数组相同。

最佳答案

我写了一个小测试程序。它访问随机位置的数组并计算这些位置的元素之和。这是针对普通数组和动态分配的数组完成的。两个数组都包含相同的数据,并且在相同的点进行访问。

使用 gfortran 和 ifort,我找不到任何大小的数组的显着差异。

这是我使用的代码。您可以调整变量 arr_size 和 num_loop 来调整用于平均时间的数组大小/运行次数。当前参数(数组大小 = 1000 万,10 次平均运行)具有以下运行时间:

经典数组平均运行时间:0.060910000280秒

动态分配数组的平均运行时间:0.060630000010 秒

第一个和第二个总和之间的差值:0.00000E+00

program alloc_test
  implicit none
  ! determines the size of the arrays.
  integer, parameter :: arr_size = 1e7
  ! sets the number of averaging runs
  integer :: num_loop = 10
  integer, dimension(arr_size) :: access
  ! pre allocated array
  real*8, dimension(arr_size) :: arr1
  ! dinamically allocated array.
  real*8, dimension(:), allocatable :: arr2
  integer :: t1, t2, clockrate, i, j
  real*8 :: temp, tot_time, sum1, sum2
  integer :: r_size
  integer, dimension(:), allocatable :: rseed
  !get random seed so the second test uses the same random numbers.
  call random_seed(size = r_size)
  allocate(rseed(r_size))
  call random_seed(get = rseed)
  call system_clock(count_rate = clockrate)
  tot_time = 0
  temp = 0
  do j = 1, num_loop, 1
    call random_number(arr1)
    access = floor(arr1 *arr_size) + 1
    call system_clock(t1)
    do i = 1, arr_size, 1
      temp = temp + arr1(access(i))
    end do
    call system_clock(t2)
    tot_time = tot_time + (t2-t1) /(1.0 * clockrate)
  end do
  sum1 = temp
  write(*,"(a,x,f15.12,x,a)") "Average elapsed time classical array:", tot_time/num_loop, "seconds"

  ! reset random seed:
  call random_seed(put = rseed)
  allocate(arr2(arr_size))
  tot_time = 0
  temp = 0
  do j = 1, num_loop, 1
    call random_number(arr2)
    access = floor(arr2 *arr_size) + 1
    call system_clock(t1)
    do i = 1, arr_size, 1
      temp = temp + arr2(access(i))
    end do
    call system_clock(t2)
    tot_time = tot_time + (t2-t1) /(1.0 * clockrate)
  end do
  write(*,"(a,x,f15.12,x,a)") "Average elapsed time dynamically allocated array:", tot_time/num_loop, "seconds"
  sum2 = temp
  write(*, "(a, e12.5)") "Difference in the sum between first and second sum: ", sum1 - sum2
end program alloc_test

关于fortran - 动态分配的数组与 Fortran 的普通数组具有相同的读写速度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68129966/

相关文章:

string - Fortran:从字符串中删除字符

linux - 如何从 Fortran 代码中删除文件?

Python glmnet "No module named _glmnet"

android - ARM/Android 中的 Fortran 编译器

c - 混合编程发布失败但调试成功

gdb - 从 GDB 中的 Fortran 多态派生数据类型中打印值

fortran - 如何学习 Fortran。问题?

C/Fortran 二维数组(基础)

c - 在 C 中修改 Fortran 数组

fortran - 声明变量时 KIND= 的用途