Do compilers recognize branching within fast loops



I have written some molecular dynamics code in fortran 95, and now I
would like to extend it so that I can turn the periodic boundary
conditions on or off. (The long term goal is parallel code)

The problem is that I feel tempted to place an if-branch inside a fast
do-loop, but I have heard that this is a bad idea. The simplest code
for calculating forces would look like this:

integer N ! number of particles
integer i,j ! iterates over particles
real(kind=8) box ! Size of the system
real(kind=8) boxinv ! Inverse size of the system
real(kind=8) x(3,N) ! Posititions of N particles in the box
real(kind=8) dr(3) ! Distance between two particles
logical, intent(in) :: usingperiodicboundaryconditions
.....

boxinv=1.0d0/box
do i=1,N
do j = ..... iterates over neighbors of i

c Calculate distance between i and j
dr(:) = x(:,i) - x(:,j)

c ----------The following looks expensive-----------
if(usingperiodicboundaryconditions)
dr(:) = dr(:) - dr(:) *box*anint(dr*boxinv)
endif

drmag2 = sum(dr**2)
if(drmag2 > cutoff**2) cycle

.... Calculate twobody (Lennard-Jones) forces between particles i
and j

end do
end do

The alternative is to place the innermost loop inside the branch. This
solution is messy because it requires me to write all my code twice
(or place it in a subroutine). The relevant parts of the code would
look like this

if(usingperiodicboundaryconditions)
do j = ..... iterates over neighbors of i
dr(:) = x(:,i) - x(:,j)
dr(:) = dr(:) - dr(:) *box*anint(dr*boxinv)
drmag2 = sum(dr**2)
.....
end do
else
do j = ..... iterates over neighbors of i
dr(:) = x(:,i) - x(:,j)
drmag2 = sum(dr**2)
....
end do
endif

The third option is to use a c-style preprocessor, but I would like to
avoid that.

Ideally my compiler (ifort) should recognize the problem, and solve it
silently by replicating the binary code, but I don't know enough about
modern compilers to guess whether or not this is actually happening.

Should I trust my compiler to optimize this code or should I try to do
something myself.

Thanks in advance

Niels

.



Relevant Pages

  • Re: Strange behavior with pointers
    ... >> developed a routine to sum the four neighbors of a specific ... This is one possible way for the compiler to come to this result. ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Strange behavior with pointers
    ... > developed a routine to sum the four neighbors of a specific row/column ... The compiler is allowed to do whatever it likes. ...
    (microsoft.public.dotnet.languages.vc)