In article <f8**************************@posting.google.com >,
za****@orgio.net (zaemin) wrote:
From a web-site that teaches optimization for c,
I saw bellow optimization rule.
int fact1_func (int n)
{
int i, fact = 1;
for (i = 1; i <= n; i++)
fact *= i;
return (fact);
}
int fact2_func(int n)
{
int i, fact = 1;
for (i = n; i != 0; i--)
fact *= i;
return (fact);
}
The author say 'fact2_func' is faster than 'fact1_func'.
That means 'i <= n' operation is more expensive than 'i != 0'.
So far, I thought all condition statements have same cost.
So I want to know the cost of condition states from the fast one to slow one.
Can anyone tell me?
No, because it is implementation dependent.
However, good compilers will often manage to transform the code you
wrote into faster code automatically, so if one were for any reason
faster than the other, then the compiler writer would usually have some
way to use the faster method.
With loops, it often helps if the compiler can determine the number of
iterations that the loop will perform before starting to execute it. If
you can write your loop in a way that makes this easy, it will often
help.
Function 1: There are three cases. If n <= 0 there are 0 iterations. If
n < INT_MAX then there are n iterations. If n == INT_MAX there will be
undefined behavior (i will be set to the maximum possible value, and
then incremented again. Not a good idea).
Function 2: There are two cases: If n >= 0 then there are n iterations.
If n < 0 you will have undefined behavior, as you start with negative i,
decrement it until it reaches the most extreme negative value, and then
decrement it further (not a good idea).
Most people write loops using <, <=, >, >= not == or !=, so compilers
are more likely to recognise these patterns and optimise for them. The
typical style is
for (i = 0; i < n; ++i)
which has 0 iterations if n <= 0 and n iterations otherwise. That style
is most likely recognised and produces fast loops.