Speed of floating point math

James Hague jamesh@REDACTED
Tue Mar 28 18:01:33 CEST 2000


Consider this simple function:

mag_squared(X,Y,Z) -> X*X + Y*Y + Z*Z.

and this little test program:

mag_test(0) -> ok;
mag_test(N) -> mag_squared(0, 1, 0), mag_test(N-1).

This takes a barely noticible amount of time for mag_test(100000), less
than 1/8 second.  Now change the last line to this:

mag_test(N) -> mag_squared(0.0, 1.0, 0.0), mag_test(N-1).

Now mag_test(100000) takes 4 seconds on the same machine; at least 32 times
slower.  Adding type guards to mag_squared makes no difference.  I haven't
torn into the runtime yet, but it's difficult to come up with a 32x
difference.  Are floating point values being heap allocated?  Is most of
the loop being optimized away in the integer version because the arguments
to mag_squared are constants?

An interesting puzzle!



More information about the erlang-questions mailing list