
February 26th, 2004, 03:12 PM
|
First Lieutenant
|
|
Join Date: Dec 2003
Location: Calgary, Canada
Posts: 762
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Re: 2.08 and Incompatible Battle Reports
Quote:
Originally posted by PhilD:
If your function calls are guaranteed to not have any side effects, the rearrangement Arryn "suggested" is actually a good move; it makes the compiled program faster by saving a (potentially costly) function call. This is a case of the compiler "helping" a sloppy programmer (and all programmers are sloppy).
Of course, if your function call has a side effect, it's a very bad move because one call will not have the same side effect as two calls. In this case, calling the dice-rolling function has a side effect, since it modifies the state of the random generator, so it's pretty important.
I don't know enough of the C specification to say whether there's a keyword to let the compiler know that a given function call is guaranteed to not have any side effects, but I suppose some compilers can be tweaked to assume that they are...
[And I don't even know whether "side effect" is the correct English translation for the French "effet de bord"; all my teaching is done in French, I admit...]
|
I'd say you translated "side effect" correctly, but in the context it sounds like the calls
code:
time_t t1 = time(0);
time_t t2 = time(0);
should not be optimized because function time has a "side effect" of returning the current time.
I understand that you're talking about the functions which are function in mathematic sense, meaning that for a given set of arguments the result will always be the same, and the return value will be the only data that will be changed.
I don't know if there's a term for such functions.
The problem comes because optimizer can not really figure out if the function has any "side effects" (let's keep calling them this way). Compiling/optimizing are performed per compilation unit and if the function in question is not residing in the same unit, optimizer can't even try to analyse the function, so it has no choice but make 2 separate calls.
Are there any optimizer which would try to do this kind of optimization? Usually, they just optimize common subexpressions, for
code:
a1 = 4 + (x + y)*n;
b1 = 8 + (x + y)*n;
they would evaluate (x+y)*n once, leave it in the register and then do additions and assignments.
This method isn't safe either, consider:
code:
void foo(int& a1, int& b1, int& x, int y, int n)
{
a1 = 4 + (x + y)*n;
b1 = 8 + (x + y)*n;
}
void ouch()
{
int z, x = 1, y = 1, n = 2;
foo(x,z,x,y,n);
}
Though for this case the optimizer often has some kind of pragmas that allow to tell that the function does not have any aliased variables.
|