473,837 Members | 1,464 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How increase a C/C++ Program speed ?

I Know C is the fastest progrmming language. However, by using some
bitwise operation you can get faster the your program.
For instance, we talk about swap function. For a integer swapping we
use this generally.

void swap(int* a,int* b){
int c;
c=*a;
*b=*a;
*b=c;
}

we use a local variable and swapping varibales with each other, it may
be expensive. We do this swap function like that:

void swap(int*a ,int *b){
*a ^= *b;
*b ^= *a;
*a ^= *b;
}

Yeah, this function swap the integers, too. But it is faster than the
first one. Also do not need a local variable.

Jul 23 '05 #1
15 4841
RAYYILDIZ wrote:
I Know C is the fastest progrmming language.
You know incorrectly. But never mind...
However, by using some
bitwise operation you can get faster the your program.
Whatever that means...
For instance, we talk about swap function. For a integer swapping we
use this generally.

void swap(int* a,int* b){
int c;
c=*a;
*b=*a;
*b=c;
Actually, you have a serious error there. It should be

int c = *a;
*a = *b;
*b = c;
}

we use a local variable and swapping varibales with each other, it may
be expensive. We do this swap function like that:

void swap(int*a ,int *b){
*a ^= *b;
*b ^= *a;
*a ^= *b;
That's a bad idea, generally.
}

Yeah, this function swap the integers, too. But it is faster than the
first one. Also do not need a local variable.


It's not faster because it doesn't work in a hypothetical case

int a = 42;
swap(&a, &a);

Unless it's proven that your original (with my corrections) swap is too
slow and affects your overall program too much, there is no need to do
that kind of micro-optimizations. Remember, "Premature optimization is
the root of all evil".

V
Jul 23 '05 #2
RAYYILDIZ wrote:
I Know C is the fastest progrmming language. I won't bite this flamebait, but:
we use a local variable and swapping varibales with each other, it may
be expensive. We do this swap function like that:
void swap(int*a ,int *b){
*a ^= *b;
*b ^= *a;
*a ^= *b;
}

Yeah, this function swap the integers, too. But it is faster than the
first one. On any CPU I've ever worked with, it won't be. It might work better for
extremely old architectures or some embedded systems that I've never
worked with, though.
Also do not need a local variable.

You are mistaken. Most architectures can't operate on two memory
operands at once, so the data must be loaded into registers. In this
case, the CPU registers can essentially be regarded as temporary variables.

Unless I'm missing something, the code produced will most likely consist
of 6 + 2 (for loading the pointers a and b into registers) memory reads,
3 xor instructions, and 3 memory writes, unless the compiler has
knowledge about the function parameters. (i.e. whether a can equal b or not)

The usual swapping approach with a temporary temporary variable will
easily be optimised by the compiler to load the data at a and b into
registers, and write them back into the reversed memory locations. The
temporary variable will most likely never even be put into memory. (2 +
2 reads, 2 writes) Even if it is put on the stack, for example because
you've disabled compiler optimisations, that only adds one read and
write each, that is still considerably less than the XOR method.

I'm probably off by a few instructions here or there, depending on the
CPU architecture, and how memory offsets are calculated, but I think my
point still stands.

The technique was used on very old register- and memory-starved systems,
as far as I know. It's no longer useful today.

~phil
Jul 23 '05 #3
On 2005-03-01 09:53:05 -0500, "RAYYILDIZ" <ra*******@gmai l.com> said:
I Know C is the fastest progrmming language.
Says who?
However, by using some
bitwise operation you can get faster the your program.
For instance, we talk about swap function. For a integer swapping we
use this generally.

void swap(int* a,int* b){
int c;
c=*a;
*b=*a;
*b=c;
}
First, you've written that incorrectly. I hope you meant:

void swap(int*a,int* b)
{
int c = *a;
*a = *b;
*b = c;
}

Second, we already have std::swap in the Standard Library:

#include <algorithm>

....
{
int i = 25;
int j = 12;
swap(i,j);
//Now i == 12 and j == 25
}
....

std::swap has the advantage that it will work with any assignable type.

we use a local variable and swapping varibales with each other, it may
be expensive. We do this swap function like that:

void swap(int*a ,int *b){
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
This is a very bad idea, for several reasons:
1) It's premature optimization.
2) It may actually be slower than the more obvious swapping algorithm
on some platforms
3) It is less readable
4) It is not always correct:

int i = 25;
int j = 25;
swap(&i,&j);
Yeah, this function swap the integers, too. But it is faster than the
first one.
Says who?
Also do not need a local variable.


Who cares?

--
Clark S. Cox, III
cl*******@gmail .com

Jul 23 '05 #4

"RAYYILDIZ" <ra*******@gmai l.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
I Know C is the fastest progrmming language. However, by using some
bitwise operation you can get faster the your program.
For instance, we talk about swap function. For a integer swapping we
use this generally. void swap(int* a,int* b){
int c;
c=*a;
*b=*a;
*b=c;
} we use a local variable and swapping varibales with each other, it may
be expensive. We do this swap function like that: void swap(int*a ,int *b){
*a ^= *b;
*b ^= *a;
*a ^= *b;
} Yeah, this function swap the integers, too. But it is faster than the
first one. Also do not need a local variable.


Have you actually measured it? On my machine, there's no significant
difference in execution time. Moreover, calling std::swap is significantly
faster than either version.

Using exclusive-or for swapping is a cute trick, but rarely useful in
practice.


Jul 23 '05 #5
RAYYILDIZ wrote:
I Know C is the fastest progrmming language. However, by using some
bitwise operation you can get faster the your program.
For instance, we talk about swap function. For a integer swapping we
use this generally.

void swap(int* a,int* b){
int c;
c=*a;
*b=*a;
*b=c;
}
we use a local variable and swapping varibales with each other, it may
be expensive. We do this swap function like that:

void swap(int*a ,int *b){
*a ^= *b;
*b ^= *a;
*a ^= *b;
}


NNNNNNNNOOOOOOO OOO!!!!!!!!!!!

The XORing version, on C++ compiler I've ever used is SLOWER once you
enable even basic optimisation.

SSSSLLLOOOWWWEE ERR!!

(sorry, but this comes up so often). Any modern compiler can easily
remove unused variables, or just keep them in a register. They aren't
stupid!

Lets see what the average compiler will do (I check g++ 3.3 at
optimisation -O1):

For your first swap function, any compiler on any optimisation level
will produce the code (sudo-assembler)

read *a into register 1
read *b into register 2
write register 1 into *b
write register 2 into *a

Your code will produce:

read *a into register 1
read *b into register 2
register 1 = register 1 XOR register 2
register 2 = register 2 XOR register 1
register 1 = register 1 XOR register 2
put register 1 into *a
put register 2 into *b

As you can see, your code is clearly taking longer :)

Chris
Jul 23 '05 #6
> we use a local variable and swapping varibales with each other, it may
be expensive. We do this swap function like that:

void swap(int*a ,int *b){
*a ^= *b;
*b ^= *a;
*a ^= *b;
}

Yeah, this function swap the integers, too. But it is faster than the
first one. Also do not need a local variable.


Depends on your compiler, processor architechture, how the turing complete
(?) system executing the code is configured and other factors someone might
kindly contribute. A neat trick but the possible speedup in a typical case
doesn't come from fact that this tiny fragment of code itself when compiled
to something is faster than what the other function would produce but rather
the fact that it might require one less register (assuming this turing
complete computing system has registers or some level of hierarchy as far as
accessing the variables is concerned speedwise) possibly reducing or
completely avoiding spilling (assuming that your computer and/or
microarchitecht ure and/or/maybe turing complete computing system and the
compiler implementation are related to the concept of spilling in any shape,
form, method, way or fashion).

Furthermore (insert previous disclaimers enmasse here for security reasons),
your compiler might implement these functions without linking time code
generation, leading to observation that the implementation uses some
fashion, form or equivalent of call/return instructions, or close
resemblance thereof concepts making the issue of avoiding spilling a moot
one from any practical point of view in terms of performance or size of the
compiled code. <- this paragraph makes some rather bold assumptions about
the state of the system you are querying the possible differences of
performance for.

However, you should not concern yourself with this level of optimization
very much as it is highly platform and compiler dependent. The fastest way
to do something is not to do it at all, if you can avoid computing
something: don't compute it. It may be faster overall to do relatively slow
operation only a few times rather than optimized operation many times. Use
std::swap and when it becomes apparent that it is too slow and actual
bottleneck in your application you might find out that no matter how fast
swap you have won't help either.. at that time you will be optimizing
something that actually matters.

I'm not saying it's not all good and beneficial, even sexy if you have the
world's fastest swap.. it's just that either of these two can be faster than
the other one..
Jul 23 '05 #7

"RAYYILDIZ" <ra*******@gmai l.com> schrieb im Newsbeitrag news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
I Know C is the fastest progrmming language. However, by using some
bitwise operation you can get faster the your program.
For instance, we talk about swap function. For a integer swapping we
use this generally.

void swap(int* a,int* b){
int c;
c=*a;
*b=*a;
*b=c;
}

we use a local variable and swapping varibales with each other, it may
be expensive. We do this swap function like that:

void swap(int*a ,int *b){
*a ^= *b;
*b ^= *a;
*a ^= *b;
}

Yeah, this function swap the integers, too. But it is faster than the
first one. Also do not need a local variable.


There is at least one compile which proves you wrong. On my machine, the simple solution using a temporary takes about 19 seconds for 1000 millions of swaps. The obfuscated version takes about 26 seconds for the same number of swaps.

Heinz
Jul 23 '05 #8
Hey, folks... I saw in Doom3 SDK code that Mr. Carmack uses this swap
trick....

So it's safe :).

Jul 23 '05 #9
Il 2005-03-01, RAYYILDIZ <ra*******@gmai l.com> ha scritto:
I Know C is the fastest progrmming language. However, by using some
bitwise operation you can get faster the your program.
For instance, we talk about swap function. For a integer swapping we
use this generally.


Does know your i396 compiler tool the instruction XCHG ?
Jul 23 '05 #10

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

Similar topics

5
1862
by: velthuijsen | last post by:
I have a function that before I modified it took around 13.75 seconds to complete after the modification it took .325 seconds to complete. the function header: (Point **Input, size_t InputSize, Point *Output, size_t OutputSize); Point is a simple x,y,z coordinate structure (3 doubles). TheDistances is an array containing room for InputSize doubles. Most of the time consumed (99%+) is in the following for loops:
14
8525
by: Sameer | last post by:
Hello, i wish to read a file of int and store into an array dynamically... the size of memory allocated finally, should just be sufficeient to store n integers. I do not know the number of integers in the file... How should I go about creating the array int array dynamically ? the file is
18
1963
by: HYRY | last post by:
I want to join two mono wave file to a stereo wave file by only using the default python module. Here is my program, but it is much slower than the C version, so how can I increase the speed? I think the problem is at line #1, #2, #3. import wave import array lfile = wave.open(lfilename) rfile = wave.open(rfilename)
3
3657
by: Jakob Petersen | last post by:
Hi, I need to increase the speed when retrieving data from a hosted SQL Server into VBA. I'm using simple SELECT statements. How important is the speed of my Internet connection? (I have 4mbits) Should I index my tables or use Stored Procedures? Or is there a kind of "flush" function or readonly function or... Or is it simply a question of the amount of data transmitted over the Internet?
1
2541
by: Kelie | last post by:
hello, would there be any speed increase in code execution after python code being compiled into exe file with py2exe? thanks, kelie
1
1490
by: AliRezaGoogle | last post by:
Dear members I am working with a 2000 GH P4 Intel, and 512GB RAM. I have a long list matrix 3000 * 15,000 of type double. I have a calculation procedure which can be executed on any single element of the matrix. Regarding to nature of this procedure, it is possible to run procedure on every element independently. I designed 30 threads. Every thread runs same procedure on equal portion of the matrix. For example rows from 0 to 100 are...
3
2276
by: Starbuck01 | last post by:
I have to write a program for my AP Computer Science Class. Here is the instructions. The Police Department is asking for help in catching those who speed. You will write a batch style program (read data from a file) where the first set of data includes the distance in feet of an area marked off on a parkway and the speed limit (miles per hour) for that parkway. The rest of the data includes the time in seconds of how long it took a driver to...
0
1118
by: Charles | last post by:
3000 rows is not a big quantity. You can load it into VC program memory, a linked list for example, and "asynchronously" load into Oracle. The connection method can be embedded SQL or ODBC. Charles "Nicke Verenius" <nicholaus_verenius@hotmail.comwrote in message news:Fw8Ba.19250$_2.494@news1.bredband.com...
10
11766
by: Devang | last post by:
Hello, I am using php script to upload file. some times if file size is too big(1GB) it takes too much time to upload. Can someone suggest me the way to increase upload speed. thanks
0
9843
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
10875
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
10566
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
9401
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...
0
7001
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5669
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
5848
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4474
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
3
3124
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.