Skip to content

Instantly share code, notes, and snippets.

@dappelha
Created October 25, 2020 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dappelha/f03cf8a6d68979eb35d3f9a4623e15ed to your computer and use it in GitHub Desktop.
Save dappelha/f03cf8a6d68979eb35d3f9a4623e15ed to your computer and use it in GitHub Desktop.
How to trick the compiler to unroll loops for you without manually unrolling the loop.
! Modern compilers with -O3 usually unroll loops when the start and stop bounds of the loop are known
! at compile time. Here is an example where I use a new secondary loop with fixed bounds to unroll by
! the amount specified in the parameter nunroll. This allows the routine to be general with only a change
! to nunroll (and a recompile) to unroll by a different amount.
program loop_unrolling
implicit none
integer :: i, ii, iend, istart
integer, parameter :: nunroll=2
iend = 11
print *, "Hello World!"
do istart = 1, iend, nunroll
print *, "istart = ", istart
do ii = 1, nunroll ! compilers usually unroll loops with compile time known bounds.
i = istart + ii-1
if(i .le. iend) then
print *, i
endif
enddo
enddo
end program loop_unrolling
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment