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

Fortran数组重复运算计时程序翻译与技术解析

Fortran数组操作计时程序(中文注释版)

程序说明

  • 核心功能:对指定长度的数组重复执行r(i) = -a(i)操作,统计总耗时与单次迭代耗时
  • 运行方式:
    • 执行命令:./program -nt T -nx N
    • 参数说明:
      • -nt T:设置迭代次数,默认值为1000
      • -nx N:设置数组元素数量,默认值为10256

完整代码

!////////////////////////////////////////////////////////////////////////////////
!   计时程序
!   使用方法:
!           ./program -nt T
!           T:   运行的迭代次数(默认值 = 1000)
!
!   功能描述:
!           针对长度为nx(默认=10256)的数组,重复T次计算a[1:nx] = -a[1:nx]
!           报告总耗时
!           报告单次迭代耗时
program main
    use iso_fortran_env, only : output_unit, real64

    implicit none

    !//////////////////////////////
    ! 计时变量
    integer :: t1, t2, count_rate, count_max, i, j
    real(real64)  :: elapsed_time

    integer, parameter :: opu=output_unit
    real(real64), allocatable :: a(:)
    real(real64), allocatable :: b(:)
    real(real64), allocatable :: c(:)
    real(real64), allocatable :: r(:)

    !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    !   问题控制参数
    integer :: niter = 1000
    integer :: nx = 10256
    !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    call grab_args(niter)
    call grab_args(nx)
    allocate(a(nx))
    allocate(b(nx))
    allocate(c(nx))
    allocate(r(nx))
  
    a(1:nx) = 1.0
    b(1:nx) = 2.0
    c(1:nx) = 5.0
 
    r = a * b + c

    write(opu,*)'循环执行 ', niter,' 次.'
    write(opu,*)'元素数量', nx, '统计中'
    call system_clock(t1, count_rate, count_max)
    do j = 1, niter
       do i = 1, nx
          r(i) = -a(i)
       enddo
    enddo

    call system_clock(t2, count_rate, count_max)
    elapsed_time = real(t2-t1) / real(count_rate)

    write(opu,*)'总耗时: ', elapsed_time
    write(opu,*)'单次迭代耗时: ', elapsed_time / niter

    deallocate(a)
    deallocate(b)
    deallocate(c)
    deallocate(r)

contains

    subroutine grab_args(numiter)
      implicit none

      integer, intent(inout)   :: numiter

      integer :: n                    ! 命令行参数数量
      integer :: i
      character(len=1024) :: argname  ! 参数键名
      character(len=1024) :: val      ! 参数值

      n = command_argument_count()
      do i=1,n,2
         call get_command_argument(i, argname)
         call get_command_argument(i+1, val)
         select case(argname)
         case('-nt')
            read(val, '(i8)') numiter
         case('-nx')
            read(val, '(i8)') nx
         case default
            write(output_unit,'(a)') ' '
            write(output_unit,'(a)') &
                 ' 未识别选项: '// trim(argname)
         end select
      enddo

  end subroutine grab_args


end program main

注:原代码中allocate(r)存在语法错误,已修正为allocate(r(nx))以匹配数组维度要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:14:53