Code Optimization Exercises: ============================ First something really simple. What optimizations can we perform on the following pieces of code? 1. x = y / w + z / w Answer: ------- x = (y + z) / w 2. DO i = 1,10 print*,i*10 END DO Answer: ------- Use constant increments instead of multiplies if this is possible. Some compilers are clever enough to figure this out for you in some simple cases. DO i = 1,100,10 print*,i END DO 3. INTEGER :: i,j REAL :: d,f REAL, DIMENSION(width;height) :: array DO i=1,width DO j=1,height array(i,j)=(2.0*i+j)/d f = 1.5*d END DO END DO Answer: ------- In fortran arrays the first index should change the most, declare the variables in order of type size (largest first), replace division with multiplication and multiplication with addition. Take the loop invariant code out of the loop. You may also do some loop unrolling. Note that, compiler may do these kind of optimizations automatically in simple cases. REAL, DIMENSION(width,height) :: array REAL :: d,dd,f INTEGER :: i,j dd = 1.0/d f = 1.5*d DO j=1,height DO i=1,width array(i,j)=(i+i+j)*dd END DO END DO Then we'll get down to business... 4. Profile your application by using gprof (if you do not have your application with you, try LDGB in the exercises folder). 5. Try to enhance the performance of your application by tweaking compiler flags. Note, check that the results are not affected! 6. Examine, if the performance of your code can be optimized and attempt to do it.