开发者

C++ performance, for versus while

开发者 https://www.devze.com 2022-12-30 21:39 出处:网络
In general (or from your experience), is there difference in performance between for and while loops?

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?

Than开发者_StackOverflowk you


Here is a nice paper on the subject.


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.


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


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.


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.


it should be negligible. an optimizing compiler should make the distinction nonexistent.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号