Erlang arithmetics

Dmitry Demeshchuk <>
Sat Oct 30 10:03:52 CEST 2010


I'm writing an article comparing Erlang and Node.js and I stumbled
upon the performance question.

My initial goal was to compare some basic arithmetics speed, like the
total distance between randomly distributed points. So, I have written
the following code for Erlang:



test(N) ->
    L = lists:seq(1, N),
    [{X0, Y0} | Points] = [{random:uniform(1000),
random:uniform(1000)} || _ <- L],
    Now = now(),
    lists:foldl(fun move_to/2, {0, {X0, Y0}}, Points),
    timer:now_diff(now(), Now).

move_to({X, Y}, {Sum, {X0, Y0}}) ->
    {Sum + math:sqrt((X - X0) * (X - X0) + (Y - Y0) * (Y - Y0)), {X, Y}}.


and the following code for Node.js:


var a = [];
for(var i = 0; i < 1000000; i++) {
    a[i] = {};
    a[i].x = Math.floor(Math.random() * 1000);
    a[i].y = Math.floor(Math.random() * 1000);

var sum = 0;

var start = (new Date()).valueOf();

for(var i = 1; i < 1000000; i++) {
    var prev = a[i-1];
    sum += Math.sqrt((a[i].x - prev.x) * (a[i].x - prev.x) + (a[i].y -
prev.y) * (a[i].y - prev.y));

var end = (new Date()).valueOf();

console.log(end - start);


There was no special tuning for Erlang and Node, both using the latest versions.
But "arith_speed:test(1000000)." from Erlang console and "node
test.js" have given me very different results: about 413 milliseconds
for Erlang and 124 milliseconds for Node. So, the difference was about
4 times! I tried to change the total number of points, and the overall
result remained the same.

Both Erlang and V8 (Google's engine that is used by Node) use IEEE
754-2008 implementation, so that's not about float type
representation. So, for now I have several probable explanations:

1. I've done something wrong and my tests suck (but that may mean that
the difference in performance may be even more significant)
2. Erlang uses type overflow check on each computation to determine if
it's time to switch from smallint to bigint.
3. Some more reasons that I don't know about or don't consider.

Also, I'm still not sure if this kind of test is good for arithmetics
comparison. On one side, it uses only pretty basic operations
(summing, multiplying and square root) but on the other side it may
involve some special computation mechanisms for Erlang that may slow
it down.

So, any help in this research is very appreciated. I understand that
this involves another platform too, but since Erlang appeared to be
slower I want to start from it first.

Thanks in advance.

Best regards,
Dmitry Demeshchuk

More information about the erlang-questions mailing list