Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C compilers and loop optimisation

Tags:

I don't have a lot of experience with how compilers actually optimise, and what the difference is between the different levels (-O2 vs -O3 for gcc for example). As such, I'm unsure whether the following two statements are equivalent for an arbitrary compiler:

for(i=0;i<10;++i){
variable1*variable2*gridpoint[i];
}

and

variable3=variable1*variable2;
for(i=0;i<10;++i){
variable3*gridpoint[i];
}

From a processing-time point of view it would make sense to only compute the product of variable1 and variable2 once as they don't change in the loop. This requires extra memory however, and I'm not sure how strongly an optimiser factors this overhead in. The first expression is the easiest to read if you have an equation from a paper/book and want to translate it to something computer-readable, but the second might be the fastest - especially for more complicated equations with a lot of unchanged variables within the loop (I have some pretty nasty non-linear differential equations which I would like to be human readable in the code). Does any of this change if I declare my variables as constants? I hope my question makes sense for an arbitrary compiler since I use both gcc, Intel and Portland compilers.