Re: Order of statements using if
On Sep 20, 3:38 pm, aeism...@gmail.com wrote:
On Sep 20, 3:00 am, James Kanze <james.ka...@gmail.com> wrote:
On Sep 19, 6:32 pm, aeism...@gmail.com wrote:
A quick question regarding how to write if/then blocks.
Do C++ compilers care in terms of execution (i.e.,
efficiency) which block in an if/then/else loop is
executed? That is, will going to the "else" block be less
efficient than using the "then" block?
Why? Does your profiler say that this is causing a
bottleneck in your code?
Well, the code I was using runs about twice as fast before I
inserted the block into the code, so it's a pretty good clue
that the if block is part of the bottleneck.
Maybe, but that could be simply the time necessary to evaluate
the condition.
My question comes because I want to know if there is any advantage in
writing the test condition to favor one block over the other. (For the
code I'm working with, one case is definitely preferred over the
other--at least 2 to 1.)
The usual rule is to write the shorter block first, provided
that this doesn't make the conditional expression harder to
read. Worrying about performance in this sort of thing is a
total waste of time.
Normally, I'd agree with you. But in this particular case,
it's for use in a scientific code. The code will pass through
this if loop on the order of billions of times during the
course of the runs. Even a 1 percent speed-up will equal
thousands of CPU hours. (Hence the question.)
My point was more that for this sort of thing, the compiler
should be able to handle whatever optimization is possible.
Back in the old days, when I was working in assembler, we'd
sometimes "out of line" the exceptional case of the if,
organizing the assembler something like:
loop {
// ...
if ( condition ) goto ExceptionalCase ;
// normal case...
EndCondition:
// ...
}
// ...
ExceptionalCase:
// ...
goto EndCondition ;
Even today (in fact, perhaps more so today), this sort of thing
can make a difference (in tight loops, of course). A good
compiler, however, should be able to pick it up, and do it for
you. (Obviously, it will need profiling information to do so.
But most modern compilers have support for profile driven
optimizations.)
If the compiler doesn't do this sort of thing automatically,
trying to reorganize the code so that it ends up with the
equivalent results will require a lot of work, and probably end
up making the code far more difficult to read. And if you leave
both branches of the if in the loop, I'd be very, very surprised
if swapping them makes a measurable difference (but it's an easy
experiment to make).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34