Do compilers recognize branching within fast loops
- From: "Niels L Ellegaard" <niels.ellegaard@xxxxxxxxx>
- Date: 12 Mar 2006 20:32:06 -0800
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
.
- Follow-Ups:
- Re: Do compilers recognize branching within fast loops
- From: s8ngsu3
- Re: Do compilers recognize branching within fast loops
- From: beliavsky
- Re: Do compilers recognize branching within fast loops
- From: glen herrmannsfeldt
- Re: Do compilers recognize branching within fast loops
- From: Greg Lindahl
- Re: Do compilers recognize branching within fast loops
- Prev by Date: Re: Number to string conversion without internal writes
- Next by Date: Re: Number to string conversion without internal writes
- Previous by thread: Using g95 with MATLAB (MAC OS X)
- Next by thread: Re: Do compilers recognize branching within fast loops
- Index(es):
Relevant Pages
|