C版:性能
#include <stdio.h>
#include <stdlib.h>
unsigned int test(unsigned int n_count) {
unsigned int c = 1;
unsigned int i;
for (i=0; i< n_count;i++) {
c += 2 * 34 + 1;
c /= 2;
c *= 39;
}
return c;
}
int main(int argc, char* argv[])
{
printf("%u\n", test(atoi(argv[1])));
}
结果:
$ gcc p2.c
$ time ./a.out 100000000
563970997
real 0m0.865s
user 0m0.864s
sys 0m0.004s
二郎版本:
-module(test2).
-export([main/1]).
-mode(compile).
calc(Cnt, Total) when Cnt > 0 ->
if Total >= 4294967296 -> Total2 = Total rem 4294967296;
true -> Total2 = Total end,
calc(Cnt - 1, trunc((Total2 + 2 * 34 + 1)/2) * 39);
calc(0, Total)->
if Total >= 4294967296 -> Total2 = Total rem 4294967296;
true -> Total2 = Total end,
io:format("~p ~n", [Total2]),
ok.
main([A])->
Cnt = list_to_integer(A),
calc(Cnt, 1).
结果:
$ erlc +native +"{hipe, [to_llvm]}" test2.erl
$ time escript test2.beam 100000000
563970997
real 0m4.940s
user 0m4.892s
sys 0m0.056s
$ erlc +native test2.erl
$ time escript test2.beam 100000000
563970997
real 0m5.381s
user 0m5.320s
sys 0m0.064s
$ erlc test2.erl
$ time escript test2.beam 100000000
563970997
real 0m9.868s
user 0m9.808s
sys 0m0.056s
如何提高erlang版本的性能? 在erlang中,我必须模拟整数溢出情况,有没有更好的方法? 甚至与HIPE,其性能是远远C.
编辑:
Python版本:
def test(n_count):
c = 1
for i in xrange(n_count):
c += 2 * 34 + 1
c /= 2
c *= 39
if c >= 4294967296:
c = c % 4294967296
return c
print test(100000000)
结果:
$ time python p2.py
563970997
real 0m17.813s
user 0m17.808s
sys 0m0.008s
$ time pypy p2.py
563970997
real 0m1.852s
user 0m0.508s
sys 0m0.128s
Erlang是不是在数字运算非常好。你可以在C中实现你的算术模块,并通过port-drivers/NIF来使用它。 –
顺便说一句,你是什么意思*整数溢出情况*? Erlang使用BigNum作为整数,所以它们不会流过... –
您可能想要从测试中排除VM启动时间测量,B/C以某种方式缓慢。但无论如何,正如已经提到的,erlang在数字处理方面不好。 – danechkin