Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
27995 Discussions

optimization: merging redundant sums into one single sum/loop

Valued Contributor I

Consider the following concise beautiful one-line Fortran code, which computes the mean of a wieghted sample of points,

mean = sum(Weight*Point) / sum(Weight)

Here  real(real64) :: Point(1:np)  contains all the data points and integer(int32) :: Weight(1:np) of the same length contains the wieghts.

However, in a loop implementation of the above code, the two sum() in the above can be merged into a single do-loop, potentially avoiding the extra looping and loop-overhead.

Is ifort smart enough to merge the two sums into a single loop with optimizations enabled, given that both Point(np) and Weight(np) are declared as automatic dummy arrays of the same length np?

0 Kudos
1 Reply
Black Belt Retired Employee

The compiler CAN merge loops. Whether it will or not depends on whether it thinks it is safe and efficient to do so. But you could do this in one loop, accumulating two sums, then do the single divide.

0 Kudos