Skip to main content
GameDev.net gamedev.net
🔒 Locked

declaring a variable inside or outside a loop - why the difference?

Started by fnm Sep 20, 2010 at 2:59 PM 5 replies 1.7k views
Original Post
fnm
fnm
I'm trying to optimize my raytracer, so I started to measure the execution time of my methods. I've noticed that there's a big difference in execution time depending on where do I declare the variables. Take a look:

Vector v(1, 1, 1);for(unsigned int i=0;i<100000000;i++){	v.normalize();}


This took 3.3426 sec to execute.

for(unsigned int i=0;i<100000000;i++){	Vector v(1, 1, 1);	v.normalize();}


This took 0.0000014 sec to execute.

Where this difference come from?
Brother Bob
Brother Bob
In the first code, the vector is visible from outside the for loop, and it may generate the code for the loop to ensure the state of the vector after the loop. In the second code, the vector is not visible outside the loop, and if the normalize function has no side effects (most likely the case), the compiler can remove it entirely.

The second code is effectively eliminated, because there are no observable change in the program.
rip-off
rip-off
Was that in Release mode, with optimisations enabled? I would expect a competent compiler would optimise away the loop.
fnm
fnm
Yes, release mode, using visual c++ 2008.
The normalize function gets called, if I put there some debug message I see it printed.
karwosts
karwosts
No, normalize is not getting called in the latter case during your benchmark. Otherwise you have a CPU that can normalize ~7000 vectors per clock cycle, which I think is a little bit beyond the capability of modern day computers.

If you put the debug in it probably recompiles it with the loop, but that's not what you're benchmarking.
[size=2]My Projects:
[size=2]Portfolio Map for Android - Free Visual Portfolio Tracker
[size=2]Electron Flux for Android - Free Puzzle/Logic Game
rip-off
rip-off
Quote:
Original post by fnm
Yes, release mode, using visual c++ 2008.
The normalize function gets called, if I put there some debug message I see it printed.

This is a side effect, meaning that the compiler will no longer optimise away the loop. To see what is going on in the original case, you'll have to examine the assembler output.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.