Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

AND or OR condition

nitya
Beginner
864 Views

Hi,

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

Say I have a check

[fortran]

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

  call add

else

  call subtract

end if

[/fortran]

Is this better than

[fortran]

if(a<0 or a > 10 or b < 0 or b > 10) then

  call add

else

 call subtract

endif

[/fortran]

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.

0 Kudos
3 Replies
Steven_L_Intel1
Employee
864 Views

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.

0 Kudos
nitya
Beginner
864 Views

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

0 Kudos
JVanB
Valued Contributor II
864 Views

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.

0 Kudos
Reply