I am wondering whether compiling with an optimization level of -O3 in gfortran is safe. By safe, I mean producing exactly the same result as when no optimization is used.
Safe.
If the results is very different from without -O3, it is likely your code somehow has a bug. Try turn on some debug information and see if there are some warnings.
For gfortran, you may also use things like -march=native, it should be similar with intel’s -xHost
There some other gfortran flags discussed here, you could search.
Optimization can involve some code reordering, modifying the rounding errors. Therefore some digits can be different in the results. But it does not necessarily mean that the result is worse. It is just slightly different…
I thought only ffast-math affects results.
Sorry, I probably answered too quicky, and -O3
avoids reordering operations. I have just tested with a real world modelling and the result is the same to the last digit with -O3
and -O0
.
I don’t remember any problems with gfortran -O3
(aside from bugs in my own code). But I had problems with ifort
, where a line of code got executed although it shouldn’t get executed, which resulted in a segmentation fault. I still think -O3
is safe, but be aware there might be problems with bugs in your own code or in the compiler. I would always run all tests with optimisation turned on, before using the program in critical situations.
Based on my experience, the debug/testing and release do not necessarily generate the same result. Numbers are typically different near the roundoff error (due to optimizations). Do not rely on this behavior even if the results look the same for some tests. There will be surprises in untested scenarios.
Things seem more complex: exactly the same results with gfortran:
0.81270250405301958
0.81270250405301958
but with ifort the last digit is different with -O0
and -O3
:
0.812702504053014
0.812702504053016
Note that I don’t know which result is the best (but I don’t care, three digits are enough for my work…).