performance - Why in C++ overwritingis is slower than writing? -
i have run piece of code manages video stream camera. trying boost it, , realized weird c++ behaviour. (i have admit realizing not know c++)
the first piece of code run faster seconds, why? might possible stack full?
faster version
double* temp = new double[n]; for(int = 0; < n; i++){ temp[i] = operation(x[i],y[i]); res = res + (temp[i]*temp[i])*coeff[i]; }
slower version1
double temp; for(int = 0; < n; i++){ temp = operation(x[i],y[i]); res = res + (temp*temp)*coeff[i]; }
slower version2
for(int = 0; < n; i++){ double temp = operation(x[i],y[i]); res = res + (temp*temp)*coeff[i]; }
edit realized compiler optimizing product between elemnts of coeff , temp. beg pardon unuseful question. delete post.
this has nothing "writing vs overwriting".
assuming results indeed correct, can guess "faster" version can vectorized (i.e. pipelined) compiler more efficiently.
the difference in in version allocate storage space temp
, whereas each iteration uses own member of array, hence iterations can executed independently.
your "slow 1" version creates (sort of) false dependence on single temp
variable. primitive compiler might "buy" it, producing non-pipelined code.
your "slow 2" version seems ok actually, loop iterations independent. why still slower? can guess due use of same cpu registers. is, arithmetic on double
implemented via fpu stack registers, interference between loop iterations.
Comments
Post a Comment