Recent

Author Topic: compilation and arithmetic operations with numbers  (Read 11983 times)

engkin

  • Hero Member
  • *****
  • Posts: 3112
Re: compilation and arithmetic operations with numbers
« Reply #15 on: October 18, 2021, 02:36:36 am »
By my understanding, what you're talking about is to pre-calculate at compile time with what is known by the compiler.

It is a basic optimization know as "Constant Folding"

Seenkao

  • Hero Member
  • *****
  • Posts: 546
    • New ZenGL.
Re: compilation and arithmetic operations with numbers
« Reply #16 on: October 18, 2021, 09:32:54 am »
By my understanding, what you're talking about is to pre-calculate at compile time with what is known by the compiler.
Yes.

А продолжение - нет. Потому что всё остальное - это ваши домыслы.
Я не предлагал менять что-то в процессе вычисления. А предлагал указать компилятору дополнительные "точки", с помощью которых компилятор будет быстрее вычислять конечный результат.

То, о чём пишите вы, не относится к компиляции. Это чистое изменение кода. И в таких ситуация решать программисту, надо делать это или нет. Но ни как не компилятору!

И покажу вам код, что предлагаю я.

Yandex translate:
And the continuation is not. Because everything else is your speculation.
I didn't suggest changing anything in the calculation process. I suggested specifying additional "points" to the compiler, with which the compiler will calculate the final result faster.

What you are writing about does not apply to compilation. This is a pure code change. And in such situations, it's up to the programmer to decide whether to do it or not. But not the compiler!

And I'll show you the code that I offer.

The original code:
Code: Pascal  [Select][+][-]
  1. for Count := 0 to MAX_TEST do    // MAX_TEST = 1000000
  2.     begin
  3.       mS1 := nn + 66 + 35;
  4.       mS2 := mS1 - 54 - 22;
  5.       mS3 := ms1 / 22;
  6.     end;              

The final code:
Code: Pascal  [Select][+][-]
  1.     n2 := 35;
  2.     n5 := 66;
  3.     n6 := 54;
  4.     mS4 := 22;
  5.     for Count := 0 to MAX_TEST do
  6.     begin
  7.       mS1 := n2 + nn + n5;
  8.       mS2 := mS1 - n6 - mS4;
  9.       mS3 := ms1 / mS4;
  10.     end;          
В итоге ни чего не поменялось, но изменённый код будет работать немного быстрее. А в больших программах вероятнее всего программа может выдать намного большее ускорение конечной программы. Хотя бы по той причине, что на большинстве участков кода используются не оптимизированные данные. Даже при вызове процедур/функций.
Оптимизировать можно много всего, даже не изменяя конечного кода программы (у меня ускорение чуть меньше 8%).

Yandex translate:
As a result, nothing has changed, but the modified code will work a little faster. And in large programs, most likely the program can give a much greater acceleration of the final program. At least for the reason that most parts of the code use non-optimized data. Even when calling procedures/functions.
You can optimize a lot of things without even changing the final program code (I have a slightly less than 8% acceleration).

P.S. хотя большинству из вас это не нужно, вы даже заморачиваться подобным не будете. / although most of you don't need it, you won't even bother with it.
« Last Edit: October 18, 2021, 09:40:40 am by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

FPK

  • Moderator
  • Full Member
  • *****
  • Posts: 118
Re: compilation and arithmetic operations with numbers
« Reply #17 on: October 31, 2021, 05:40:40 pm »
Code: Pascal  [Select][+][-]
  1. Besides, It's bad thing to rearrange FP arithmetic, will yield a different result.
  2.  
+1

I have added an optimization for this but it is only active in "fastmath" mode: https://gitlab.com/freepascal.org/fpc/source/-/commit/5a617cd1082e80008559a012673db2eecb6304bf (in fastmath mode the compiler does transformations which are mathematically valid but might break due to floating point number behaviour).

Seenkao

  • Hero Member
  • *****
  • Posts: 546
    • New ZenGL.
Re: compilation and arithmetic operations with numbers
« Reply #18 on: November 01, 2021, 02:09:03 am »
FPK, thank you!
I have added an optimization for this but it is only active in "fastmath" mode: https://gitlab.com/freepascal.org/fpc/source/-/commit/5a617cd1082e80008559a012673db2eecb6304bf (in fastmath mode the compiler does transformations which are mathematically valid but might break due to floating point number behaviour).
"fastmath" не обязателен. Достаточно произвести проверку что сумма/разность чисел идущих друг за другом не теряют своего конечного значения (первое значение не поглощает значение второго числа).
Первое - это проверка по длине. Попадание в длину числа, чтоб не было потерь (при учёте, что числа сами не выходят за пределы и не теряют свой смысл. Но и тогда это можно делать. Это не зависит от компилятора).
Второе (уже не обязательное) проверка изменения конечного числа. Эта проверка не может быть первой, потому что тут больше фактическую роль играет длина каждого числа.

Точнее преобразование не должно идти когда первое число намного больше второго (если это полезная информация).

Google translate:
"fastmath" is optional. It is enough to check that the sum / difference of the numbers following each other do not lose their final value (the first value does not absorb the value of the second number).
The first is checking by length. Hitting the length of a number so that there is no loss (taking into account that the numbers themselves do not go beyond the limits and do not lose their meaning. But even then it can be done. It does not depend on the compiler).
The second (no longer required) check of the change in the final number. This check cannot be the first, because the length of each number plays a more actual role here.

More precisely, the conversion should not occur when the first number is much larger than the second (if this is useful information).

for example:
z := n + 50 + 4   ->  (50 + 4) does not lose its meaning
z := n + 3434563748272345 + 443    -> (3434563748272345 + 443) the meaning of the expression disappears

let be
z := n + num01 + num02
then (exaggerated)
Code: Pascal  [Select][+][-]
  1. num03 := num01 + num02;
  2. if num03 <> num01 then
  3.   if num03 - num01 = num01 then
  4.     the condition is satisfied, we transform.

если в формулах стоят целые числа, а рассчитываться будут числа с плавающей точкой, то мы можем эти действия произвести с целыми числами. Это не конечный код, а только предварительный. А с целыми числами мы можем получить более точный результат.

Всего хорошего!

google translate:
if the formulas contain integers, and floating point numbers will be calculated, then we can perform these actions with integers. This is not final code, only preliminary code. And with integers, we can get a more accurate result.

Good luck! ;)
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

 

TinyPortal © 2005-2018