Lu与C/C++、Forcal、MATLAB、Python、Lua等各种语言的速度比较(二)

2014-11-24 12:41:19 · 作者: · 浏览: 1
upperlim=(upperlim<

test(0,0,0);
printf("Number of solutions is %ld, %d seconds\n", sum,(int)(time(0)-tm));
}

VC运行结果:

15 Queens
Number of solutions is 2279184, 6 seconds

3 Matlab与Lu普通函数调用效率

Matlab 2009a的测试代码:

f=@(x,y,z,t)x+y+z;
tic;
s=0;
for x=0:1000
for y=0:100
for z=0:100
s=s+f(x,y,z);
end
end
end
s
toc

s =

6.126720600000000e+009

Elapsed time is 9.546717 seconds.

将函数写成m文件后效率会提高,如下例:

%file xyz.m
function c=xyz(x,y,z)
c=x+y+z;
end

测试代码:

tic;
s=0;
for x=0:1000
for y=0:100
for z=0:100
s=s+xyz(x,y,z);
end
end
end
s
toc

s =

6.126720600000000e+009

Elapsed time is 4.724592 seconds.

Lu代码:

f(x,y,z)=x+y+z;
main(:t,s,x,y,z)=
t=clock(),
s=0,
x=0, while{x<=1000,
y=0, while{y<=100,
z=0, while{z<=100,
s=s+f(x,y,z),
z++
},
y++
},
x++
},
o{"s=",s,", time=",[clock()-t]/1000.};

Lu运行结果:

s=6126720600, time=4.015

4 Matlab与Lu的递归函数调用效率

以Fibonacci递归程序为例进行比较。

Matlab 2009a的Fibonacci函数定义:

function k=fib(n)

if n == 0
k=0;
return;
else if n == 1
k=1;
return;
else
k=fib(n - 1) + fib(n - 2);
return;
end

end

运行结果:

tic;
fib(30)
toc

ans =

832040

Elapsed time is 26.315245 seconds.

Lu的Fibonacci函数及代码:

SetStackMax(1000);
F(n)= which{
n == 0,
return(0),
n == 1,
return(1),
return [F(n - 1) + F(n - 2)]
};
main(:t)= t=clock(), o{"F(30)=",F(30),", time=",[clock()-t]/1000.};

Lu运行结果:

F(30)=832040, time=0.875

5 变步长辛卜生二重求积法

C/C++代码:

#include "stdafx.h"
#include
#include
#include "time.h"
#include "math.h"

double simp1(double x,double eps);
void fsim2s(double x,double y[]);
double fsim2f(double x,double y);

double fsim2(double a,double b,double eps)
{
int n,j;
double h,d,s1,s2,t1,x,t2,g,s,s0,ep;

n=1; h=0.5*(b-a);
d=fabs((b-a)*1.0e-06);
s1=simp1(a,eps); s2=simp1(b,eps);
t1=h*(s1+s2);
s0=1.0e+35; ep=1.0+eps;
while (((ep>=eps)&&(fabs(h)>d))||(n<16))
{
x=a-h; t2=0.5*t1;
for (j=1;j<=n;j++)
{
x=x+2.0*h;
g=simp1(x,eps);
t2=t2+h*g;
}
s=(4.0*t2-t1)/3.0;
ep=fabs(s-s0)/(1.0+fabs(s));
n=n+n; s0=s; t1=t2; h=h*0.5;
}
return(s);
}

double simp1(double x,double eps)
{
int n,i;
double y[2],h,d,t1,yy,t2,g,ep,g0;

n=1;
fsim2s(x,y);
h=0.5*(y[1]-y[0]);
d=fabs(h*2.0e-06);
t1=h*(fsim2f(x,y[0])+fsim2f(x,y[1]));
ep=1.0+eps; g0=1.0e+35;
while (((ep>=eps)&&(fabs(h)>d))||(n<16))
{
yy=y[0]-h;
t2=0.5*t1;
for (i=1;i<=n;i++)
{
yy=yy+2.0*h;
t2=t2+h*fsim2f(x,yy);
}
g=(4.0*t2-t1)/3.0;
ep=fabs(g-g0)/(1.0+fabs(g));
n=n+n; g0=g; t1=t2; h=0.5*h;
}
return(g);
}

void fsim2s(double x,double y[])
{
y[0]=-sqrt(1.0-x*x);
y[1]=-y[0];
}

double fsim2f(double x,double y)
{
return exp(x*x+y*y);
}

int main(int argc, char *argv[])
{
int i;
double a,b,eps,s;
clock_t tm;

a=0.0; b=1.0; eps=0.0001;
tm=clock();
for(i=0;i<100;i++)
{
s=fsim2(a,b,eps);
}
printf("s=%e , 耗时 %d 毫秒。\n", s, (clock()-tm));
}

C/C++结果:

s=2.698925e+000 , 耗时 78 毫秒。

-------

matlab 2009a代码:

%file fsim2.m
function s=fsim2(a,b,eps)
n=1; h=0.5*(b-a);
d=abs((b-a)*1.0e-06);
s1=simp1(a,eps); s2=simp1(b,eps);
t1=h*(s1+s2);
s0=1.0e+35