AND or OR condition

AND or OR condition

Hi,

I am trying to find out if using an AND instead of an OR condition is more efficient.

Say I have a check

if(.NOT. (a > 0 and a < 10 and b > 0 and b < 10))then
  call add
else
  call subtract
end if

Is this better than

if(a<0 or a > 10 or b < 0 or b > 10) then
  call add
else
 call subtract
endif

For an AND condition, it is enough if one of the condition is FALSE, whereas for the OR it has to check all the conditions. Is this correct?

I ask since I have a grid of 1283 cells and I need to do the above check for each cell. I am not sure if this takes a lot of time, but I would like to optimize it if possible.

Thanks in advance.

4 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.

Fortran does not have short-circuit evaluation. The compiler is free to evaluate the expression to any degree of completeness it chooses as long as the result is logically equivalent.

My advice to you is not to waste any time nano-optimizing such things.  Write the code so that a human can understand it clearly and let the compiler worry about optimization. It can do a lot of reassociation and test inversion on its own.

Steve - Intel Developer Support

Hi,

"The compiler is free to evaluate the expression to any degree of completeness it chooses as long as the result is logically equivalent."

Ok, thanks for your reply Steve. That answers my query.

Nitya

De Morgan says

.NOT. (a > 0 .and. a < 10 .and. b > 0 .and. b < 10)

is equivalent to:

a <= 0 .OR. a >= 10 .OR. b <= 0 .OR. b >= 10

So you might want to leave things in the state where you understand the conditions, provided there is such a state. I personally find that I have trouble with complicated conditions and frequently get them wrong. Something about Murphy's principle of binary selection. Also it may be a good time to enable standards checking for the file that has the complex conditions because by default ifort happily compiles complete garbage that isn't even valid Fortran as a logical condition. Also look for ways to make the condition more readable, such as

.NOT. (all([a,b] > 0 .and. [a,b] < 10))

so that when you change the interval it changes automatically for both variables or even

temp = [a,b]

.NOT. (all(temp > 0 .and. temp < 10))

so that changing one variable for the lower bound automatically changes it for the upper bound.

Leave a Comment

Please sign in to add a comment. Not a member? Join today