Reputation: 1554
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;
Upvotes: 2
Views: 116
Reputation:
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
Upvotes: 1
Reputation: 5980
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.
Upvotes: 5
Reputation: 735
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.
Upvotes: 2