Measure before you change

The classic trap is premature optimization: rewriting code that was never slow, guided by intuition rather than evidence. The reliable order is the reverse — measure the program, find where its time actually goes, change only that, and measure again. Without a before number, no after number proves anything.

Finding hot spots

Runtime concentrates: in most scientific programs a small fraction of the routines account for most of the execution time, and those routines are the hot spots. Profiling tools report per-routine times and call counts and point straight at them. If a profiler is not at hand, a simpler instrument works too: time a few candidate regions by hand and compare.

For hand timing, Fortran provides standard intrinsics: cpu_time reports processor time used by the program, and system_clock reports wall-clock ticks from the system clock. Calling one before and after a region and subtracting gives the region's cost:

real :: t1, t2 call cpu_time(t1) ! ... region being measured ... call cpu_time(t2) print *, 'Region seconds: ', t2 - t1

What to change first

Rank the hot spots by how much of the total runtime each one owns, and take the largest first. Then ask the cheap questions before rewriting: is the loop order friendly to memory layout? Are whole-array expressions doing work a hand-written loop would do less efficiently? Would a higher optimization level help? Often the answer is a one-line change, not a redesign.

Keeping a baseline

Record the original timings — the baseline — before the first change, and re-time after every change on the same input. A change that improves one case can slow another, and without the saved numbers the regressions go unnoticed. When a change does not beat the baseline, it is simply reverted; the baseline is what makes performance work honest.