473,732 Members | 2,196 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

code optimization- Removing if .. else conditions in for loops

Hello,

I need help in removing if ..else conditions inside for loops. I have
used the following method but I am not sure whether it has actually
helped.
Below is an example to illustrate what I have used.
Original code :

c= 0 ;
for (i=0; i<999; i++)
{
if (a > B)
c++ ;
}

Modified code for speed optimization

c= 0 ;
for (i=0; i<999; i++)
{
c += (a > B) ;
}

As per my reasoning, the logical expression is evaluated but no
conditional branching instructions should be generated. This should
avoid any pipeline stalls.
However, I havent found any document confirming my belief !
Any comments, suggestions or references will be a big help !

Thanks & Regards

Dec 5 '05 #1
24 8626
"Kunal" <ku************ *@gmail.com> writes:
I need help in removing if ..else conditions inside for loops. I have
used the following method but I am not sure whether it has actually
helped.
Below is an example to illustrate what I have used.
Original code :

c= 0 ;
for (i=0; i<999; i++)
{
if (a > B)
c++ ;
}

Modified code for speed optimization

c= 0 ;
for (i=0; i<999; i++)
{
c += (a > B) ;
}


The only way you can find out whether this makes a difference is
by measuring. My guess is that it will make no difference with
most compilers.

Note that the evaluation of `a > b' may itself require a branch.
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Dec 5 '05 #2
"Kunal" <ku************ *@gmail.com> writes:
I need help in removing if ..else conditions inside for loops. I have
used the following method but I am not sure whether it has actually
helped.
Below is an example to illustrate what I have used.
Original code :

c= 0 ;
for (i=0; i<999; i++)
{
if (a > B)
c++ ;
}

Modified code for speed optimization

c= 0 ;
for (i=0; i<999; i++)
{
c += (a > B) ;
}

As per my reasoning, the logical expression is evaluated but no
conditional branching instructions should be generated. This should
avoid any pipeline stalls.
However, I havent found any document confirming my belief !
Any comments, suggestions or references will be a big help !


You're assuming that the code generated for (a > B) won't involve any
conditional branches.

Any decent compiler is likely to generate similar or identical code
for both forms.

It's usually best to write your code as clearly as possible and let
the compiler worry about micro-optimization. Attempting to do
low-level optimization yourself is likely to make the compiler's job
more difficult.

First rule of optimization: Don't do it.
Second rule of optimization (advanced users only): Don't do it yet.

If you really need to do this kind of micro-optimization, perhaps
because the loop is in a performance-critical part of your program
(because you've measured it), you can probably examine the assembly
language generated by your compiler -- or you can write the code in
assembly language yourself.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 5 '05 #3
In article <11************ **********@g14g 2000cwa.googleg roups.com>,
"Kunal" <ku************ *@gmail.com> wrote:
Hello,

I need help in removing if ..else conditions inside for loops. I have
used the following method but I am not sure whether it has actually
helped.
Below is an example to illustrate what I have used.
Original code :

c= 0 ;
for (i=0; i<999; i++)
{
if (a > B)
c++ ;
}

Modified code for speed optimization

c= 0 ;
for (i=0; i<999; i++)
{
c += (a > B) ;
}

As per my reasoning, the logical expression is evaluated but no
conditional branching instructions should be generated. This should
avoid any pipeline stalls.

Did you measure how long it takes?

The most important rule of optimisation: Don't optimise until you have
measured it.

(There are several most important rules of optimisation, this is just
one of them. I bet some more will be posted. This one always applies:
Never, ever optimise without measuring. )
Dec 5 '05 #4


Kunal wrote On 12/05/05 17:02,:
Hello,

I need help in removing if ..else conditions inside for loops. I have
used the following method but I am not sure whether it has actually
helped.
Below is an example to illustrate what I have used.
Original code :

c= 0 ;
for (i=0; i<999; i++)
{
if (a > B)
c++ ;
}

Modified code for speed optimization

c= 0 ;
for (i=0; i<999; i++)
{
c += (a > B) ;
}
Even faster (probably):

c = (a > B) ? 999 : 0;
i = 999;
As per my reasoning, the logical expression is evaluated but no
conditional branching instructions should be generated. This should
avoid any pipeline stalls.
However, I havent found any document confirming my belief !
Any comments, suggestions or references will be a big help !


See Ben Pfaff's response.

--
Er*********@sun .com

Dec 5 '05 #5
On 2005-12-05, Eric Sosman <er*********@su n.com> wrote:


Kunal wrote On 12/05/05 17:02,:
Hello,

I need help in removing if ..else conditions inside for loops. I have
used the following method but I am not sure whether it has actually
helped.
Below is an example to illustrate what I have used.
Original code :

c= 0 ;
for (i=0; i<999; i++)
{
if (a > B)
c++ ;
}

Modified code for speed optimization

c= 0 ;
for (i=0; i<999; i++)
{
c += (a > B) ;
}


Even faster (probably):

c = (a > B) ? 999 : 0;
i = 999;


Though presumably he was doing more in the loop, you're correct.
Dec 5 '05 #6


Jordan Abel wrote On 12/05/05 18:00,:
On 2005-12-05, Eric Sosman <er*********@su n.com> wrote:

Kunal wrote On 12/05/05 17:02,:
Hello,

I need help in removing if ..else conditions inside for loops. I have
used the following method but I am not sure whether it has actually
helped.
Below is an example to illustrate what I have used.
Original code :

c= 0 ;
for (i=0; i<999; i++)
{
if (a > B)
c++ ;
}

Modified code for speed optimization

c= 0 ;
for (i=0; i<999; i++)
{
c += (a > B) ;
}


Even faster (probably):

c = (a > B) ? 999 : 0;
i = 999;

Though presumably he was doing more in the loop, you're correct.


That was the point I was trying to make, indirectly:
It's silly to micro-optimize pseudocode. If the O.P.
responds to my tongue-in-cheek suggestion by showing us
what's actually going on in the loop, we might have some
better ideas about how to optimize it -- or whether it's
even worth the bother.

--
Er*********@sun .com

Dec 5 '05 #7
On 5 Dec 2005 14:02:46 -0800, in comp.lang.c , "Kunal"
<ku************ *@gmail.com> wrote:
Hello,

I need help in removing if ..else conditions inside for loops.
Why - have you proved that they're inefficient?
c += (a > B) ; As per my reasoning, the logical expression is evaluated but no
conditional branching instructions should be generated. This should
avoid any pipeline stalls.


This would be /highly/ hardware specific, and depend very very much on
your compiler's efficiency.

As a general rule its a bad idea to try to outsmart your compiler,
until and unless you can prove its inefficient. You may end up simply
making your code slower. A good compiler might realise it could unroll
the loop and discard a whole bunch of the ifs, and your 'improvement'
might prevent that for some reason.

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 5 '05 #8
Kunal wrote:
Hello,

I need help in removing if ..else conditions inside for loops. I have
used the following method but I am not sure whether it has actually
helped.
Have you tested the code to see if it is too slow? Have you done
profiling to see where the code is spending its time? Have you made sure
that you are using an efficient algorithm? All these things should come
before spending time on a question like this.
Below is an example to illustrate what I have used.
Original code :

c= 0 ;
for (i=0; i<999; i++)
{
if (a > B)
c++ ;
}

Modified code for speed optimization

c= 0 ;
for (i=0; i<999; i++)
{
c += (a > B) ;
}

As per my reasoning, the logical expression is evaluated but no
conditional branching instructions should be generated. This should
avoid any pipeline stalls.
Anything like that is highly specific to the processor, compiler,
specific version of the compiler, the settings of the compiler and the
surrounding code.
However, I havent found any document confirming my belief !
It is very unlikely there is *any* documentation that will tell you
which is faster, since it might depend on a hole host of things.
Any comments, suggestions or references will be a big help !


Rule one of optimisation:
Don't do it.

Write the code to do the right thing in an understandable (to a human)
manner and let the optimiser that is almost certainly part of your
compiler package do its job.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Dec 6 '05 #9
Kunal wrote:
Hello,

I need help in removing if ..else conditions inside for loops. I have
used the following method but I am not sure whether it has actually
helped.
Below is an example to illustrate what I have used.
Original code :

c= 0 ;
for (i=0; i<999; i++)
{
if (a > B)
c++ ;
}

Modified code for speed optimization

c= 0 ;
for (i=0; i<999; i++)
{
c += (a > B) ;
}

As per my reasoning, the logical expression is evaluated but no
conditional branching instructions should be generated. This should
avoid any pipeline stalls.


On the ARM, a natural way to compile the if (assuming variables in
registers, which is plausible here) is:

CMP a, B
ADDEQ c, c, #1

Two instructions, no pipeline break. I can't see a compiler generating
better code for your `c += (a > B)` statement, and it would be easy for
it to generate much /worse/ code.

Morals: (a) measure before you consider optimising; (b) straightforward
code plays to the compiler's strengths.

--
Chris "another virtual machine" Dollin
"Certainly the absence of a smiley is not a syntax error or a constraint
violation, and therefore doesn't require a diagnostic." (Richard
Heathfield)
Dec 6 '05 #10

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

Similar topics

3
3331
by: PWalker | last post by:
Hi, I have written code that I would like to optimize. I need to push it to the limit interms of speed as the accuracy of results are proportional to runtime. First off, would anyone know any resources that explains how to optimize code i.e. give some rules on c++ optimization? e.g. using memcpy to copy an array (which i have done). Also, what is the best sorting algorithm out there for sorting an array of of size 100 or less? I have...
8
1949
by: Hagen | last post by:
Hi, I have a question that you probably shouldn´t worry about since the compiler cares for it, but anyways: When you run your compiler with optimization turned on (eg. g++ with -Ox flag) and your program gets significantly faster than without, did you write bad code/ have a bad design? Cause what happens in those optimization steps is, I think, mostly
12
6198
by: WantedToBeDBA | last post by:
Hi all, db2 => create table emp(empno int not null primary key, \ db2 (cont.) => sex char(1) not null constraint s_check check \ db2 (cont.) => (sex in ('m','f')) \ db2 (cont.) => not enforced \ db2 (cont.) => enable query optimization) DB20000I The SQL command completed successfully. db2 => insert into emp values(1,'m')
14
3141
by: joshc | last post by:
I'm writing some C to be used in an embedded environment and the code needs to be optimized. I have a question about optimizing compilers in general. I'm using GCC for the workstation and Diab compiler for the embedded target. My question is about how compilers optimize certain code sequences. As an example, take the code below. Will the compiler eliminate the actual function call to foo() in the object code generated and just store...
11
1817
by: junky_fellow | last post by:
What are the basic guidelines to write an optimised code. What points should one keep in mind for this ? Is this purely architecture or complier specific ? Are there any general techniques that are valid for all architectures ?
9
1563
by: cyberscout | last post by:
OK I have some code which I didn't write and I'm toying with whether I need to tidy it up. In the code is the line shown in Example 1 Exampe 1: sprintf(stringvariable, "%s", "String"); Is it any worse than simply putting.
10
2145
by: Mike | last post by:
Is it still true that the managed C++ compiler will produce much better opimizations than the C# compiler, or have some of the more global/aggressive opimizations been rolled into the 2005 compiler? Are simple common sub-expressions and loop invariants optimized out in the current optimizer? thanks, m
88
8061
by: Peter Olcott | last post by:
Cab you write code directly in the Common Intermediate language? I need to optimize a critical real-time function.
30
3538
by: galiorenye | last post by:
Hi, Given this code: A** ppA = new A*; A *pA = NULL; for(int i = 0; i < 10; ++i) { pA = ppA; //do something with pA
31
2276
by: somenath | last post by:
Hi All, I was going through one of the exercise of one C tutorial . In that they have given one small code and asked about the output. #include <stdio.h> int main(void) { int x = 0xFFFFFFF0; signed char y;
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8774
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
9307
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...
0
9181
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
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.