I am implementing an elemental function that will be called a huge number of
times. The function receives a single integer argument and returns a result
corresponding to the integer argument. The code is as shown below:
Elemental function MyFunc(i) result(Result)
integer(4), intent(in) :: i
real(8) :: Residual
select case (i)
case (1)
result = ...
.
.
.
case (~10^2)
result = ...
case default
result = 12345678910.d0
end select
end function
My question is if a compiler translates the case statement to a number of
successive if-then-else if statements (like c compilers translate the switch
structure) or if it uses a more efficient selection structure? Would it be
more efficient to write the case statement as:
select case (i)
case (1:50)
if (i<25)then
...
else
...
end if
case (51:100)
if (i<75)then
...
else
...
end if
case default
result = 12345678910.d0
end select
Kind Regards
Stig Kildegård
Jan
>My question is if a compiler translates the case statement to a number of
>successive if-then-else if statements (like c compilers translate the switch
>structure) or if it uses a more efficient selection structure?
Most C and Fortran compilers have a variety of selection structures,
and try to pick a good one based on how many cases there are and how
dense they are. For example, if you had cases 1 through 100 plus
default, most compilers will use a table of pointers, and after
checking that the variable is between 1 and 100, fetch the pointer and
branch to it. That's pretty efficient.
greg
what about
select case (i)
case (1:24)
...
case (24:50)
...
case (51:74)
...
case (75:100)
...
case default
result = 12345678910.d0
end select
and avoid the if-then-elses altogether? I'm assuming that your actual problem is similar to the
code snippet you posted (which it probably isn't). I don't know if it makes the code more or
less efficient, but future maintainers of the code will thank you for making it
readable/understandable.
cheers,
paulv
--
Paul van Delst Religious and cultural
CIMSS @ NOAA/NCEP purity is a fundamentalist
Ph: (301)763-8000 x7274 fantasy
Fax:(301)763-8545 V.S.Naipaul
Thank you. That was exactly what i wanted to know.
Kind Regards
Stig
The CASE is more efficient than an IF-THEN-ELSE because the tests involve
constant values. Only one expression, that in the SELECT CASE, is evaluated
for testing, whereas for Ifs many might have to be. It analagous to the old
computed GOTO.
Regards,
Mike Metcalf