您的位置:首页 > 编程语言

基于fibonacci数列的几种编程语言的运算速度比较

2010-11-29 20:05 288 查看
所有的程序源码如下:

fib.m (MATLB2010B)

function f=fib(n)
if n==0 || n==1
f=n;
else
f=fib(n-2)+fib(n-1);
end

fib.erl (Erlang 5.8.1)

-module(fib).
-export([test/0]).

test()->
fib(40).

fib(0) -> 1;
fib(1) -> 1;
fib(N) -> fib(N-1) + fib(N-2).

fib.py (python2.6)

# enable psyco compiler
import psyco
psyco.full()

def fib(n):
if n == 0 or n == 1:
return n
else:
return fib(n-1) + fib(n-2)

print fib(40)

mlton_fib.sml (mlton20100608)

fun fib (n) = if n=0 then 0 else if n=1 then 1 else fib(n-2) + fib(n-1);
val _ =(
print(Int.toString(fib 40)),
print "/n"
);

fib1.hs (haskell platform 2010.2.0.0)

fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n-2) + fib(n-1)

main =
print (fib 40)

fib2.hs (haskell platform 2010.2.0.0)

import Control.Parallel

fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = l `pseq` r `pseq` l+r
where
l = fib (n-1)
r = fib (n-2)

main =
print (fib 40)

fib.fs (f#2.0)

let rec fib n =
if n=0 then 0
elif n=1 then 1
else fib(n-2)+fib(n-1)

let x=fib 40

fib.cpp (gcc4.4)

#include <cstdio>
int fib(int n)
{
if (n < 2) {
return 1;
}
return fib(n - 2) + fib(n - 1);
}

int main(int argc, char ** argv) {
printf("Fib(%d): %d/n", 40, fib(40));
return 0;
}

test_fib.m

%========================= fibonacii ============================
%% MATLAB
disp('MATLAB')
tic,fib(29),toc %注意是29, 就已经很慢了, 下面都是算到40

%% Erlang
disp('Erlang')
!erlc +native fib.erl
tic,eval('!erl -noshell -s fib test -s init stop'),toc

%% python
disp('python')
tic,eval('!fib.py'),toc

%% SML (mlton)
!D:/MLton/bin/mlton.bat -verbose 0 mlton_fib.sml
disp('SML(mlton)')
tic,eval('!mlton_fib.exe'),toc

%% haskell(ghc)
disp('haskell(ghc) *1*')
!ghc --make -O2 fib1.hs -o hs_fib1.exe
tic,eval('!hs_fib1.exe'),toc
disp('haskell(ghc) *2*')
!ghc --make -O2 fib2.hs -o hs_fib2.exe
tic,eval('!hs_fib2.exe'),toc

%% F#
!"C:/Program Files/Microsoft F#/v4.0/fsc" fib.fs -o fs_fib.exe
tic,eval('!fs_fib.exe'),toc

%% c++
disp('c++')
!g++ -O3 fib.cpp -o c++_fib.exe
tic,eval('!c++_fib.exe'),toc

在MATLAB命令行下运行, 计算机配置Windows XP SP3, Intel Core 2 Duo CPU T5870 2.0GHZ, RAM3.0G(某一次的测试结果):

>> test_fib
MATLAB
Elapsed time is 12.714680 seconds.
Erlang
Elapsed time is 16.976639 seconds.
python
Elapsed time is 7.685962 seconds.
SML(mlton)
Elapsed time is 3.277170 seconds.
haskell(ghc) *1*
Elapsed time is 2.436861 seconds.
haskell(ghc) *2*
Elapsed time is 2.547725 seconds.
F#
Elapsed time is 3.312573 seconds.
c++
Elapsed time is 1.132945 seconds.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: