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

如何在Intel Fortran环境下将程序/循环执行时间写入Output.txt?

在VS2010+Intel Fortran 2011中记录程序/循环执行时间到Output.txt

嘿,刚好我对这个环境下的计时需求很熟悉,给你两个靠谱的实现方案,都是在你的编译器版本里完全可用的:

方法一:用Intel Fortran内置的高精度计时函数(代码层面直接实现)

Intel Fortran支持两种常用的计时函数,cpu_time()和system_clock(),前者统计CPU占用时间,后者统计实际流逝的墙钟时间,你可以根据需求选。下面是具体的实现步骤和代码示例:

1. 程序整体执行时间记录

在程序的开头和结尾分别记录时间点,计算差值后写入文件:

program main
    implicit none
    real :: start_time, end_time, total_time
    integer :: file_unit

    ! 记录程序开始时间
    call cpu_time(start_time)

    ! --------------------------
    ! 你的程序主体代码放在这里
    ! --------------------------

    ! 记录程序结束时间
    call cpu_time(end_time)
    total_time = end_time - start_time

    ! 打开并写入Output.txt
    open(newunit=file_unit, file='Output.txt', status='replace', action='write')
    write(file_unit, '(A, F10.4, A)') '程序整体执行时间: ', total_time, ' 秒'
    close(file_unit)

end program main

2. 特定循环的执行时间记录

针对do或者do while循环,只需要在循环前后加时间点记录,然后把结果追加到文件里(注意打开文件时用status='old', position='append'):

program main
    implicit none
    real :: loop_start, loop_end, loop_time
    integer :: i, file_unit

    ! 初始化Output.txt
    open(newunit=file_unit, file='Output.txt', status='replace', action='write')
    write(file_unit, '(A)') '=== 各循环执行时间统计 ==='
    close(file_unit)

    ! 示例1:DO循环计时
    call cpu_time(loop_start)
    do i = 1, 1000000
        ! 循环内的业务代码
    end do
    call cpu_time(loop_end)
    loop_time = loop_end - loop_start

    ! 追加结果到文件
    open(newunit=file_unit, file='Output.txt', status='old', position='append', action='write')
    write(file_unit, '(A, F10.4, A)') 'DO循环(1e6次)执行时间: ', loop_time, ' 秒'
    close(file_unit)

    ! 示例2:DO WHILE循环计时
    call cpu_time(loop_start)
    i = 1
    do while(i <= 500000)
        ! 循环内的业务代码
        i = i + 1
    end do
    call cpu_time(loop_end)
    loop_time = loop_end - loop_start

    ! 追加结果到文件
    open(newunit=file_unit, file='Output.txt', status='old', position='append', action='write')
    write(file_unit, '(A, F10.4, A)') 'DO WHILE循环(5e5次)执行时间: ', loop_time, ' 秒'
    close(file_unit)

end program main

提示:如果需要微秒级的高精度计时,可以用system_clock(),它返回整数计数,结合count_rate计算实际时间,代码示例:

integer :: start_count, end_count, count_rate
call system_clock(start_count, count_rate)
! 待计时的代码块
call system_clock(end_count)
loop_time = real(end_count - start_count) / real(count_rate)

方法二:利用Intel Parallel Studio XE的性能分析工具(可视化统计)

如果你不想写代码,也可以用Intel Parallel Studio XE 2011自带的VTune Amplifier工具,它能自动统计程序中各个循环、函数的执行时间,生成详细的性能报告。不过这个工具是可视化分析,如果你必须把结果写入Output.txt,还是方法一更直接。

注意事项

  • 确保VS2010项目正确配置了Intel Fortran编译器:右键项目→属性→配置属性→常规,确认平台工具集为Intel Fortran
  • 如果newunit在你的版本中不支持(2011版大概率支持),可以手动指定文件单元号,比如integer, parameter :: file_unit = 10,然后用open(10, file='Output.txt', ...)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:22:28