473,805 Members | 2,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to optimize for loop?

I heard for(i=0;i<20;i+ +)
{
do-something;
}

Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?

Nov 15 '05 #1
10 14355
>I heard for(i=0;i<20;i+ +)
{
do-something;
}

Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?


Assuming for the moment that do-something does not contain break or
continue, and it uses but does not alter i, some people consider this an
optimization (loop unrolling):

do {
i = 0;
do-something;
i = 1;
do-something;
i = 2;
do-something;
i = 3;
do-something;
i = 4;
do-something;
i = 5;
do-something;
i = 6;
do-something;
i = 7;
do-something;
i = 8;
do-something;
i = 9;
do-something;
i = 10;
do-something;
i = 11;
do-something;
i = 12;
do-something;
i = 13;
do-something;
i = 14;
do-something;
i = 15;
do-something;
i = 16;
do-something;
i = 17;
do-something;
i = 18;
do-something;
i = 19;
do-something;
i = 20;
} while (0);

Gordon L. Burditt
Nov 15 '05 #2
Gordon Burditt wrote:
I heard for(i=0;i<20;i+ +)
{
do-something;
}

Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?

Assuming for the moment that do-something does not contain break or
continue, and it uses but does not alter i, some people consider this an
optimization (loop unrolling):

do {
i = 0;
do-something;
i = 1;
do-something;
i = 2;
do-something;
i = 3;
do-something;
i = 4;
do-something;
i = 5;
do-something;
i = 6;
do-something;
i = 7;
do-something;
i = 8;
do-something;
i = 9;
do-something;
i = 10;
do-something;
i = 11;
do-something;
i = 12;
do-something;
i = 13;
do-something;
i = 14;
do-something;
i = 15;
do-something;
i = 16;
do-something;
i = 17;
do-something;
i = 18;
do-something;
i = 19;
do-something;
i = 20;
} while (0);

Gordon L. Burditt

In the same way, googlr for Duff's device
Zara
Nov 15 '05 #3
Hi,

It depends on what is "do-something". The optimization can be loop
unrolling, moving loop envarient code out side of the loop, common
sub-expression elimination,... . It depends on your code inside the
loop.

Regards,
Raju

Bhan wrote:
I heard for(i=0;i<20;i+ +)
{
do-something;
}

Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?


Nov 15 '05 #4
"Bhan" <sw*******@gmai l.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
I heard for(i=0;i<20;i+ +)
{
do-something;
}

Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?


The above is exactly equivalent to:

i = 0;
while (i < 20) {
do-something;
++i;
}

It is obvious that the first time the condition is tested (before entering
the loop) it will be true, so there is no need to actually do the test. The
test can be moved to the bottom of the loop:

i = 0;
do {
do-something;
++i;
} while (i < 20);

If the value of i is not used except to control the number of iterations,
the following may be better in some cases:

i = 20;
do {
do-something;
} while (--i);

Another possibility already mentioned is loop unrolling. This increases code
size but may not actually increase performance. In particular, unrolling
tests (eg if "do-something" contains one or more "if" statements) may
actually decrease performance.

The loop may be partially unrolled, eg:

/* if the value of i is used: */
i = 0;
do {
do-something;
++i;
do-something;
++i;
} while (i < 20);

/* or, if the value of i is not used */
i = 0;
do {
do-something;
do-something;
++i;
} while (i < 10);

Or the loop may be fully unrolled, in which case there is no loop anymore.

However, all of this is best left to the compiler to figure out, until and
unless such optimisation helps a previously-identified performance
bottleneck.

Alex
Nov 15 '05 #5
On Mon, 05 Sep 2005 21:37:36 -0700, Bhan wrote:
I heard for(i=0;i<20;i+ +)
{
do-something;
}

Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?


If the loop can be usefully optimised the compile will propbably do so.
There's no reason to assume that an EQUIVALENT while or do-while loop will
result in different generated code.

Lawrence

Nov 15 '05 #6
Alex Fraser wrote:
"Bhan" <sw*******@gmai l.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
I heard for(i=0;i<20;i+ +)
{
do-something;
}

Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?

The above is exactly equivalent to:

i = 0;
while (i < 20) {
do-something;
++i;
}


.... provided `do-something' doesn't `continue' ...

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 15 '05 #7
"Eric Sosman" <es*****@acm-dot-org.invalid> wrote in message
news:td******** ************@co mcast.com...
Alex Fraser wrote:
"Bhan" <sw*******@gmai l.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
I heard for(i=0;i<20;i+ +)
{
do-something;
}

Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?


The above is exactly equivalent to:

i = 0;
while (i < 20) {
do-something;
++i;
}


... provided `do-something' doesn't `continue' ...


Indeed, I should have thought of that. All of what I wrote assumes no
"continue".

Alex
Nov 15 '05 #8
Bhan wrote on 06/09/05 :
I heard for(i=0;i<20;i+ +)
{
do-something;
}

Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?


Not really. You could eventually unroll the loop, but the benefit
should be negligible. Do measurements to be sure.

do-something; /* #1 */
do-something; /* #2 */
do-something; /* #3 */
....
do-something; /* #19 */
do-something; /* #20 */

(if you have a unixoïd box, use the times command... very handy)

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

I once asked an expert COBOL programmer, how to
declare local variables in COBOL, the reply was:
"what is a local variable?"
Nov 15 '05 #9

"Bhan" <sw*******@gmai l.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
I heard for(i=0;i<20;i+ +)
{
do-something;
}

Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?


Only if you're using a primitive compiler. Modern compilers will generate
the same code for:

for (i=0;i<20;i++) { ... }

i=0; while(i<20) { ... i++; }

i=0; do { ... } while (++i < 20);

and even:

i=0;
L1: if (i >= 20) goto L2;
{ ... }
i++;
goto L1;
L2:

Try the various forms and output the assembler language, and compare. If
you're interested in optimizing code, you'll need a precise way of timing it
to see how you're doing:
http://www.digitalmars.com/techtips/timing_code.html

-Walter
www.digitalmars.com free C, C++, D compilers
Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2406
by: Rune | last post by:
Is it best to use double quotes and let PHP expand variables inside strings, or is it faster to do the string manipulation yourself manually? Which is quicker? 1) $insert = 'To Be'; $sentence = "$insert or not $insert. That is the question."; or
7
2587
by: Daniel Vallstrom | last post by:
I am having trouble with floating point addition because of the limited accuracy of floating types. Consider e.g. x0 += f(n) where x0 and f are of some floating type. Sometimes x0 is much larger than f(n) so that x0 + f(n) == x0. For example, x0 could be 2**300*(1.1234...) while f(n) is 2**100*(1.4256...). If x0 + f(n) == x0 I still sometimes want the addition of f(n) to x0 to have some effect on x0. A good solution seems to be to update...
10
4570
by: MariusI | last post by:
I stumbled over an optimization (or lack of one, to be specific) when viewing IL opcodes generated by the compiler using ms .net 2003. I was testing fast pixel manipulation using Bitmap.LockBits and unsafe pointers to iterate over an image's pixels. The inner-loop looked like this: for (int x = 0; x < _buffer.Width*_buffer.Height; x++) { // do manipulations here.. }
3
1743
by: Egbert Nierop \(MVP for IIS\) | last post by:
Hi, Out of curiousity, I sometimes look at the produced assembly after compilation in release mode. What you often see, is that CPP, always fully addresses registers to copy values from a to b... While stosb,stosw, stosd etc and the same for movs are one statement, and internally use registers ESI and EDI (source, destination) to copy data.
16
3549
by: Claudio Grondi | last post by:
Sometimes it is known in advance, that the time spent in a loop will be in order of minutes or even hours, so it makes sense to optimize each element in the loop to make it run faster. One of instructions which can sure be optimized away is the check for the break condition, at least within the time where it is known that the loop will not reach it. Any idea how to write such a loop? e.g.
15
2530
by: kenneth | last post by:
I was trying to use multiple thread to optimize my following code, but met some problems, anyone can help me? k are initialized. int computePot() { int i, j; for( i=0; i<500; i++ ) { for( j=0; j<i-1; j++ ) {
26
3239
by: a.mil | last post by:
I am programming for code-speed, not for ansi or other nice-guy stuff and I encountered the following problem: When I have a for loop like this: b=b0; for (a=0,i=0;i<100;i++,b--) { if (b%i) continue; a=1; }
9
1918
by: TF | last post by:
Hello all, I made a ASP.NET 2.0 site that shows possible "recipes" for paint colors stored in an access dbase. Basically, 1000 colors are stored with specific RGB values in separate columns. A user sees all the colors listed on the page with hyperlinks that open the "mixes" page. The mixes page goes through each record, compares it with all other records in a ratio up to "maxratio". If it finds a ratio that matches the redvalue of...
11
1664
by: inihility | last post by:
This is actaully a really simple recursion (for-loop), but I'm having some trouble optimizing it so that it would run faster. for (int i = 0; i < 50; i++) { a = getNumber(i); } Right now it takes around 40-50 seconds to run. I've already tried loop unrolling, but that didn't optimize it at all.
14
2539
by: andreyvul | last post by:
I have this loop (all variables are pointers): for (foo = bar; foo baz; foo--) *(foo+1) = *foo; How do I optimize the pointer swap so that it uses -- and ++ or unary +- instead of +1 (if possible - I don't want to have more #defines than code)? IOCCC winners can really help me with this :P
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10617
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10364
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10370
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5545
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4328
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3849
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.