In general (or from your experience), is there difference in performance between for and while loops?
What if they are doubly/triply nested?
Is vectorization (SSE) affected by loop variant in g++ or Intel compilers?
Thank you
Efficiency, and While vs For Using for: % Time elapsed: 0.0010001659 seconds. Using while: % Time elapsed: 0.026000023 seconds. The main reason that While is much slower is because the while loop checks the condition after each iteration, so if you are going to write this code, just use a for loop instead.
Performance Benchmark Also, the execution speed varies significantly between the fastest contestant and the looser while loop: for-each loops are more than six times faster than while loops. Even the for-range loop is nearly two times faster than the while loop.
It is used for complex initialization. For is entry controlled loop. While is also entry controlled loop. used to obtain the result only when number of iterations is known.
The main difference between the for 's and the while 's is a matter of pragmatics: we usually use for when there is a known number of iterations, and use while constructs when the number of iterations in not known in advance.
VS2015, Intel Xeon CPU
long long n = 1000000000;
int *v = new int[n];
int *v1 = new int[2*n];
start = clock();
for (long long i = 0, j=0; i < n; i++, j+=2)
v[i] = v1[j];
end = clock();
std::cout << "for1 - CPU time = " << (double)(end - start) / CLOCKS_PER_SEC << std::endl;
p = v; pe = p + n; p1 = v1;
start = clock();
while (p < pe)
{
*p++ = *p1;
p1 += 2;
}
end = clock();
std::cout << "while3 - CPU time = " << (double)(end - start) / CLOCKS_PER_SEC << std::endl;
for1 - CPU time = 4.055
while3 - CPU time = 1.271
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With