How do i write a code to optimize a given code??
How do i write a code to optimize a given code??
How long is a piece of string?
How long does infinity go on for?
How many stars are there?
How does Billy Chrystal still get work?
You could do a few things:
Use define macros instead of functions IF POSSIBLE. For example:
... could be replaced by:Code:int cube(int x) { return x * x * x; }
You should also look into bit shifting, and there's things you can do with loops.Code:#define CUBE(x) x * x * x
Not yet, have to think of one...
Minimizing the number of instructions in the center of a nested loop always helps, but the best way to optimize code is to have an efficient algorithm in the first place, then you have no need to do piddling code tweaks.
>#define CUBE(x) x * x * x
should be
#define CUBE(x) (x) * (x) * (x)
-Prelude
My best code is written with the delete key.
Your compiler will likely be able to optimize far better than you can.
Quzah.
Hope is the first step on the road to disappointment.
As Prelude states, the most important thing for you as a programmer is to have a very effective algorithm. Other things you could do to increase performance:
1. Use as much constants as possible so you don't need to recalculate things. Especially in loops performing the same calculations use a lot of time.
2. Avoid very small functions, such as leech gave for example, replace them by macros. Function calls take a lot of time.
3. Keep your code as simple as possible.
In some cases you could use math tricks to improve calculations. For example, when needing to add a lot of numbers:
1 + 2 + 3 + .. + N = S
N + .. + 3 + 2 + 1 = S
(N + 1) + .. + (N + 1) = 2 S
-> S = N (N + 1) / 2
Another thing you could do is take a look at the assembly code and do some optimizing, if you have configured your compiler as optimizing, then it will be quite hard. Especially when you have less or no experience in writing/optimizing assembly code.
> How do i write a code to optimize a given code
1. start with a design
2. choose the best algorithms to implement that design
3. write clear code - if it's obvious to use, then it will be to the compiler.
4. Profile it to make sure you know where the hotspots are
5. Make damn sure it works before you try 6.
6. Fiddle around with all the silly tricks, often repeated without foundation, just because someone found a special case with some compiler 10 years ago, and this technique has become an urban legend in how to optimise code.
Most decent compilers know about all the good optimisations which work (like *2 can be done as <<1, BUT only if its an advantage for that particular machine).