2

The below code in unix takes ~9s reported by time command.

int main() { double u = 0; double v = 0; double w = 0; int i; for (i = 0;i < 1000000000;++i) { v *= w; u += v; } printf("%lf\n",u); } 

I don't understand why the execution times almost double when i change v *= w;withv *= u;

2
  • 2
    w is always zero. The compiler is probably smart enough not to run that loop at all in the first case since v will also always be zero, and thus u too. (Might be harder to figure out with the interdependency between u and v.) Commented Feb 10, 2013 at 16:31
  • 1
    Did you look at the generated code? Commented Feb 10, 2013 at 16:32

3 Answers 3

5

When you change v *= w to v *= u then there is an inter-dependency between the 2 statements. Hence, the first statement has to be completed before executing u += v which could be the reason for the increased performance as the compiler can't parallelize the execution.

Sign up to request clarification or add additional context in comments.

Comments

2

Probably because the compiler sees that w is never modified, and so can be compiled into a constant whereas the variable u is modified and so must have its own memory.

Comments

1

Compiler optimizes v*= w; to v = 0; and the probably u += v to u = 0; So those operations never happen.

Here is the test i did. Every version was done 10 times and averaged.

for (i = 0;i < 1000000000;++i) { v *= w; u += v; } 

4.0373 seconds



for (i = 0;i < 1000000000;++i) { v *= u; u += v; } 

7.3733 seconds



for (i = 0;i < 1000000000;++i) { v *= 0; u += 0; } 

4.0149 seconds

3 Comments

why it doesn't do the same with v *= u; since is 0 as well
Probably can't optimize v *= u and u += v out since they are dependant on each other.
@curious it takes an extra step of reasoning though (it first has to find out that v is constant zero, then that u never changes and remains zero - in the other case, it just has to see that w is constant zero), that could make a difference.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.