在 Ubuntu 上测试 Fortran 程序的运行速度/性能,常见做法有下面几种,从简单到专业。
time 测运行时间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
gfortran test.f90 -O2 -o test
time ./test
输出示例:
real 0m1.234s
user 0m1.230s
sys 0m0.004s
real:实际耗时user:CPU 用户态时间sys:系统调用时间✅ 适合:快速测整体运行时间
system_clockprogram 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
或写脚本算平均。
gprof(函数级分析)gfortran test.f90 -O2 -pg -o test
./test
gprof ./test gmon.out
可以看到:
perf(Linux 原生,非常强)sudo apt install linux-tools-common
perf stat ./test
示例输出:
Performance counter stats for './test':
1.25 seconds time elapsed
还能看:
如果你装了 ifort:
ifort test.f90 -O3 -o test
通常比 gfortran 快。
-O2 或 -O3implicit none-O3 -march=native)如果你愿意,可以:
我可以帮你针对性优化和测速。