Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ performance, for versus while

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

like image 809
Anycorn Avatar asked May 21 '10 01:05

Anycorn


People also ask

Which is faster for or while in C?

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.

Are for or while loops faster?

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.

Which is better for or while loop in C?

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.

Is for better than while?

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.


1 Answers

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

like image 86
Peter Zhilkin Avatar answered Oct 07 '22 18:10

Peter Zhilkin