温馨提示×

ubuntu如何测fortran速

小樊
46
2026-10-18 21:15:20
栏目: 智能运维

在 Ubuntu 上测试 Fortran 程序的运行速度/性能,常见做法有下面几种,从简单到专业。


一、最基础:用 time 测运行时间

1. 写一个简单的 Fortran 程序

program test
    implicit none
    integer :: i
    real :: x
    x = 0.0
    do i = 1, 100000000
        x = x + sqrt(real(i))
    end do
    print *, x
end program test

2. 编译

gfortran test.f90 -O2 -o test

3. 测时间

time ./test

输出示例:

real    0m1.234s
user    0m1.230s
sys     0m0.004s
  • real:实际耗时
  • user:CPU 用户态时间
  • sys:系统调用时间

✅ 适合:快速测整体运行时间


二、程序内部计时(更精确)

使用 system_clock

program timing
    implicit none
    integer :: i, start, finish, rate
    real :: x

    call system_clock(start, rate)
    x = 0.0
    do i = 1, 100000000
        x = x + sqrt(real(i))
    end do
    call system_clock(finish)

    print *, "Time (s):", real(finish - start) / real(rate)
end program timing

编译运行:

gfortran timing.f90 -O2 -o timing
./timing

✅ 优点:不依赖系统命令
✅ 精度高(毫秒级)


三、多测几次取平均(推荐)

for i in {1..5}; do time ./test; done

或写脚本算平均。


四、性能分析工具(高级)

1. gprof(函数级分析)

gfortran test.f90 -O2 -pg -o test
./test
gprof ./test gmon.out

可以看到:

  • 每个函数耗时
  • 调用次数

2. perf(Linux 原生,非常强)

sudo apt install linux-tools-common
perf stat ./test

示例输出:

 Performance counter stats for './test':

      1.25 seconds time elapsed

还能看:

  • CPU 周期
  • 缓存命中率
  • 分支预测

3. Intel Fortran(ifort,可选)

如果你装了 ifort:

ifort test.f90 -O3 -o test

通常比 gfortran 快。


五、常见提速建议

  • 编译加 -O2 或 -O3
  • 避免不必要的数组拷贝
  • 使用 implicit none
  • 循环内减少函数调用
  • 向量化(-O3 -march=native)

如果你愿意,可以:

  • 告诉我你的 Fortran 代码
  • 或你想测的是 数值计算 / IO / 并行

我可以帮你针对性优化和测速。

0 踩