问题
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
回答1:
Here is a nice paper on the subject.
回答2:
Any intelligent compiler won't really show a difference between them. A for
loop is really just syntactic sugar for a certain form of while
loop, anyways.
回答3:
This is something easily ascertained by looking at disassembly. For most loops, they will be the same assuming you do the same work.
int i = 0;
while (i < 10)
++i;
is the same as
for (int i = 0; i < 10; ++i)
;
As for nesting, it really depends on how you configure it but same setups should yield same code.
回答4:
Should be zero difference, but do check as I've seen really crappy, older versions of GCC create different code ARM/Thumb code between the two. One optimized away a compare after a subtract to set the zero flag where as the other did not. Was very lame.
Nesting again should make no difference. Not sure on SSE/Vectorization stuff, but again I'd expect there to be no difference.
回答5:
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
回答6:
it should be negligible. an optimizing compiler should make the distinction nonexistent.
来源:https://stackoverflow.com/questions/2879145/c-performance-for-versus-while