Recent

Author Topic: Efficient coding ?  (Read 2815 times)

zoimutante

  • New Member
  • *
  • Posts: 34
Efficient coding ?
« on: July 18, 2018, 07:56:01 pm »
I'm relativity new to the world of programming, and I find a little bit hard to find some information about efficient coding in Pascal. For instance, in channels about C or C++ almost everybody knows that is more efficient to multiple than divide, like: 100*0,50 in the place of 100/2 that is because processors do it faster. There is any place where a can find this kind of tips about Free Pascal ?
And that is my code:

program ExerciciosLogicaPower;
var base,power,result,counter:integer;
begin
write ('Type the base: ');
readln (base);
write ('Type the power: ');
readln (power);
counter:=1;
result:=base;
while counter <> power do
begin
result:=result*base;
counter:=counter+1;
end;
write (result);
end.
What could I do to make it more efficient ? (I did it just as an logic exercise, Pascal have power, just like C have pow, but it is an exercise.

Handoko

  • Hero Member
  • *****
  • Posts: 5130
  • My goal: build my own game engine using Lazarus
Re: Efficient coding ?
« Reply #1 on: July 18, 2018, 08:44:51 pm »
Usually using div, * 0.5, inc are faster. It should apply on many languages, but in Lazarus you can set the optimization to level 3 or 4 and let the compiler do it for you.
Lazarus main menu > Project > Project Options > Compiler Options > Compilation and Linking > Optimization levels

Code performance optimization is an interesting topic to learn and it needs time. It is very important in game programming. It takes me years of experience to improve this skill and now still learning mostly from performing tests and reading from books.

Some of the most basic things to do are using less complex algorithms, usually but not always simpler is faster than complex algorithms. Also pay attention on loops, put larger loops in the inside and smaller loops at the outside. Another things you can do are exit the block immediately when you found the result, using efficient variable types, caching the result.

And for you information, premature optimization is a sin in programming. It makes the code harder to read, increase the risk of bugs and harder to debug. So you should prefer easier maintainable code over optimized code. You said you're new in programming, so I don't recommend you to learn it now. :D

And here if you still want to learn optimization:
https://www.freepascal.org/docs-html/current/prog/progch11.html#x236-25000011
« Last Edit: July 18, 2018, 08:51:29 pm by Handoko »

ASerge

  • Hero Member
  • *****
  • Posts: 2222
Re: Efficient coding ?
« Reply #2 on: July 18, 2018, 10:58:03 pm »
And that is my code:
...
What could I do to make it more efficient ?
For starters it would be nice to make it correct. Do you consider negative values?
One of the advantages of Free Pascal is that everything goes in the source code. Additional optimization can be seen in the implementation of Math.IntPower.

wp

  • Hero Member
  • *****
  • Posts: 11855
Re: Efficient coding ?
« Reply #3 on: July 18, 2018, 11:37:14 pm »
I don't see much to improve here, maybe for the sake of readability use a "for" loop instead of a "while" loop. And from the logics of the code I would begin with result := 1 in order to allow the exponent 0:
Code: Pascal  [Select][+][-]
  1. program ExerciciosLogicaPower;
  2. var base,power,result,counter:integer;
  3. begin
  4.   write ('Type the base: ');
  5.   readln (base);
  6.   write ('Type the power: ');
  7.   readln (power);
  8.   result:=1;
  9.   for counter := 1 to power do
  10.     result:=result*base;
  11.   write (result);
  12. end.

The most efficient point of optimization is what happens inside loops. Precalculate as much as possible outside the loop. Suppose your exercise would be to calculate the power of sin(x). You could do it like this:

Code: Pascal  [Select][+][-]
  1. program TestPowerSinX;
  2. var
  3.   result: Double;
  4.   x, power, counter:integer;
  5. begin
  6.   write ('Type x (in degrees): ');
  7.   readln (x);
  8.   write ('Type the power: ');
  9.   readln (power);
  10.   result:=1;
  11.   for counter := 1 to power do
  12.     result:=result*sin(x/180*pi);
  13.   write (result);
  14. end.

You see what I mean? The term "sin(x/180*pi)" does not change inside the loop. Therefore precalculate it outside the loop and use the precalculated value inside the loop:

Code: Pascal  [Select][+][-]
  1. program TestPowerSinX;
  2. var x, sinx, power, result, counter:integer;
  3. begin
  4.   write ('Type x (in degrees): ');
  5.   readln (x);
  6.   sinx := sin(x/180*pi);
  7.   write ('Type the power: ');
  8.   readln (power);
  9.   result:=1;
  10.   for counter := 1 to power do
  11.     result:=result*sinx;
  12.   write (result);
  13. end.

440bx

  • Hero Member
  • *****
  • Posts: 3944
Re: Efficient coding ?
« Reply #4 on: July 19, 2018, 02:09:31 am »
For instance, in channels about C or C++ almost everybody knows that is more efficient to multiple than divide, like: 100*0,50 in the place of 100/2 that is because processors do it faster. There is any place where a can find this kind of tips about Free Pascal ?

You asked about making the code efficient from an execution viewpoint, that is, code that runs fast.  There is nothing wrong with wanting to write code that runs fast _as long as_ it is not at the detriment of maintainability (it very often is.)

When it is necessary to make code as fast as possible, first you pick the fastest algorithm, that will have a much greater effect on speed than attempting to optimize code.  Once you've got the fastest/best algorithm to accomplish the goal then, you look at the assembly code the compiler generated.  Sometimes you can change the source and have the compiler generate better code.  Often, if you really want maximum speed, you rewrite some of the code, usually short sequences, in assembly language.

It's really important to keep in mind that optimization for speed should extremely rarely be done at the expense of maintainability.  Particularly when processors are so fast.  Saving 100 clock cycles on a series of instructions that doesn't get executed very often results in an imperceptible gain in time given that processors execute well over a couple billion instructions per second these days.  Not mentioning that there are multiple execution units.  Pick an algorithm that can be parallelized before worrying about divisions, multiplications or shifts.

C programmers are notorious for creating code that is unreadable, incomprehensible and thus unmaintainable.  That's simply poor programming.  The priorities when writing a program are, 1. make it correct, 2. make it easy to maintain, 3. make it readable (decently formatted and commented) 4. 1, 2 & 3 for the next 99 times and then, make it fast.  Fast and good are NOT the same thing.  First, make it good, then amuse yourself making it faster.

One of the best books to learn programming ever written is Oh! Pascal by Doug Cooper.  You can get an older edition for just a few bucks.  The book is worth its weight in gold.  Not only he teaches to program in Pascal, he teaches the reader how to think in order to write good programs.  Reading that book is the best thing you can do for yourself.  After that pick a good book on algorithms, the second edition of Robert Sedgewick's Algorithms is my favorite because he presents the algorithms in Pascal pseudocode.    After having read "oh! pascal" read a few of Per Brinch Hansen's books, those are a treat. 

Hope that helps.


« Last Edit: July 19, 2018, 02:31:01 am by 440bx »
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

Handoko

  • Hero Member
  • *****
  • Posts: 5130
  • My goal: build my own game engine using Lazarus
Re: Efficient coding ?
« Reply #5 on: July 19, 2018, 05:01:38 am »
What @440bx said are very true.

Novice programmers usually like to write smart and fast code. As a newbie, I learned several optimization tricks and for making it faster I even wrote some libraries in Assembly language. The result is very hard to maintain codes. After I grow more experience, now performance optimization is at the lowest position in my priority. Computers at the present day run very fast, they have MMX, SSE, SSE2, SSE3 and SSE4 for making the execution faster. So lets the compiler to optimize the code based on the hardware you're targeting.

FastCode is a website that contains libraries of optimized source code. There you can learn how experts doing the optimization in Pascal.
https://en.wikipedia.org/wiki/FastCode
http://fastcode.sourceforge.net/

A good book is very important for programmers, it can boost your skill. I have Code Complete 2nd Edition. It's really a good book suitable for beginners and intermediates.
https://en.wikipedia.org/wiki/Code_Complete

 

TinyPortal © 2005-2018