Compiler Optimisation

We are doing some numeric calculations for university directly in c++, so it's as fast as possible.

One thing which makes c++ such fast are the compiler optimisations which helps to reduce the amount of code and speed things up by applying some logic.

For example

if (a + b > b)

can be converted to

if (a > 0)

You think this is a good optimisation? Often yes but in general no. Here is an example which cost me more then one day of debugging/deassembling etc.

Let's assume you want to calculate something to a certain precision, let's choose 10^-8.
So to be able to find out that something a is exactly enough you can do the following trick.

  • Get a value which is in the range of the actual result
  • Calculate range_value = value * wanted_precision / maximum_precision
    To explain this you have to know that doubles([1]) has only a certain amount of memory. So if you multiple them with a high number
    it looses some precision at the end. So the maximum_precision is a very small number, so you effective calculate it with a high number.
  • Now compare the value a1 and a2, from which a1 is the value with the lower precision and a2 the value of the higher precision.
    So

    if (range_value + a1 != range_value + a2)

    This code returns false if a1 and a2 have just a difference of "wanted_precision", because the range_value has just a certain precision at the end.

Now comes the compiler WTF:

It optimizes the following code

while ((int_schatz + int_1 != int_schatz + int_2))

to

while ((int_1 != int_2))

and booooooom it doesn't work anymore.

The used compiler was g++(4.5.2). The problem didn't appeared in the university with an old compiler version.
And as always you develop a bit and debug a lot.

Add new comment