[erlang-questions] Erlang shows its slow face!

Bernard Duggan <>
Sat Nov 13 09:39:59 CET 2010

On 13/11/10 18:37, Gilberto Carmenate García wrote:
> Hi all!
> I have been doing tests to Erlang I found this funny stuff that makes
> Pythagorean Triplets
> pythag(N) ->
>      [ {A,B,C} ||
>          A<- lists:seq(1,N),
>          B<- lists:seq(1,N),
>          C<- lists:seq(1,N),
>          A+B+C =<  N,
>          A*A+B*B =:= C*C].
> I tested it agains an implementation I made in C# so, and takes 14
> secounds in my pc to do with 300 numbers in Erlang however in c# is just
> a secound, even when C# runs under VM too.
> So I did all possible ways for me to implement differents manners in
> Erlang looking for speed and all is the same, listed as  follows:
> So my question is, there are any way to do that even more fast, why 3
> nestes fors structs in C# are more effients that lists:foldr or
> lists:foreach in Erlang.
Okay, the first and most obvious improvement to that code above is to 
change it slightly to:

pythag(N) ->
     L = lists:seq(1,N),
     [ {A,B,C} ||
         A <- L,
         B <- L,
         C <- L,
         A+B+C =< N,
         A*A+B*B =:= C*C].

That sped it up on my laptop from 4 seconds to 3.5. If you're really 
after speed in erlang, though, a good thing to try is HiPE. Add 
"+native" to your erlc command options. That sped it up (for me) to 1 
second for your code and .5 of a second for my version.  Bear in mind 
that HiPE carries tradeoffs in terms of tracing/debugging etc.

As far as your question, though, the first thing I'd say is that if 
you're using Erlang for high-performance numerical analysis, you've 
chosen the wrong language. I love Erlang to bits, but that's not its 
strength. Part of this stems from the fact that when you have a number 
(A, B, C), it's always treated as an having an arbitrary size (people 
more familiar with the guts of the VM please feel free to correct me 
here...). That means that if you want to store more than 32 or 64 bits 
in it, you can do so with zero modification to your code. That's 
brilliant and can be really useful, but the tradeoff is the performance 
hit you take on any arithmetic operation - and it's that hit, I suspect, 
that you're seeing here.



More information about the erlang-questions mailing list