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

2014-11-24 12:41:19 · 作者: · 浏览: 6
while 1 do
i = i+1
local temp = zr * zi
local zr2 = zr*zr
local zi2 = zi*zi
zr = zr2-zi2+cr
zi = temp+temp+ci
if (zi2+zr2 > BAILOUT) then
return i
end

if (i > MAX_ITERATIONS) then
return 0
end
end

end

function mandelbrot()
local t = os.clock()
for y = -39, 38 do
for x = -39, 38 do
if (iterate(x/40.0, y/40) == 0) then
io.write("*")
else
io.write(" ")
end
end
io.write("\n")
end
io.write(string.format("Time Elapsed %f\n", os.clock() - t))
end

mandelbrot()

运行输出图形与前面相同,仅给出运行时间:

Time Elapsed 0.860000

Python的代码及运行时间。


#!/usr/local/bin/python
# by Daniel Rosengren

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator:
def __init__(self):
stdout.write('Rendering...')
for y in range(-39, 39):
stdout.write('\n')
for x in range(-39, 39):
i = self.mandelbrot(x/40.0, y/40.0)

if i == 0:
stdout.write('*')
else:
stdout.write(' ')

def mandelbrot(self, x, y):
cr = y - 0.5
ci = x
zi = 0.0
zr = 0.0
i = 0

while True:
i += 1
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci

if zi2 + zr2 > BAILOUT:
return i
if i > MAX_ITERATIONS:
return 0

t = time.time()
Iterator()
stdout.write('\nPython Elapsed %.02f' % (time.time() - t))

运行结果:

Python Elapsed 2.84

=======================

完成相同功能的Lu代码如下:


mandelbrot(x, y : cr,ci,zi,zr,i,temp,zr2,zi2) =
{
cr = y - 0.5,
ci = x,
zi = 0.0,
zr = 0.0,
i = 0,

(1).while {
i ++,
temp = zr * zi,
zr2 = zr * zr,
zi2 = zi * zi,
zr = zr2 - zi2 + cr,
zi = temp + temp + ci,
if [zi2 + zr2 > 16, return (i)],
if [i > 1000, return (0)]
}

};

main (:i,x,y,old,now) = {

old=clock(),
y = -39,
while{ y < 39,
o("\r\n"),
x = -39,
while{ x < 39,
i = mandelbrot(x/40.0, y/40.0),
which{ i==0,
o("*"),
o(" ")
},
x++
},
y++
},
now=clock(),
o["\r\nLu Elapsed ",(now-old)/1000.0]
};

运行时输出的图形与C程序相同,在演示程序DemoLu32.exe(这是个windows程序)中的运行时间为:

Lu Elapsed 5.657

从运行结果可看出,Lu用的时间与c++相比,为5.657:0.25=22.628:1。

因C/C++、Forcal、Lua等均使用控制台程序,故设计加载Lu并演示以上程序的C/C++控制台程序如下:


#include
#include
#include
#include "lu32.h"

#pragma comment( lib, "lu32.lib" )

using namespace std;

void _stdcall LuMessage(wchar_t *pch) //输出动态库信息,该函数注册到Lu,由Lu二级函数调用
{
wcout< }
void main(void)
{
void *hFor; //表达式句柄
luINT nPara; //存放表达式的自变量个数
LuData *pPara; //存放输入自变量的数组指针
luINT ErrBegin,ErrEnd; //表达式编译出错的初始位置和结束位置
int ErrCode1,ErrCode2; //错误代码
void *v;
wchar_t mandelbrot[]=L"mandelbrot(x, y : cr,ci,zi,zr,i,temp,zr2,zi2) =\r\n{\r\n cr = y - 0.5,\r\n ci = x,\r\n zi = 0.0,\r\n zr = 0.0,\r\n i = 0,\r\n (1).while {\r\n i ++,\r\n temp = zr * zi,\r\n zr2 = zr * zr,\r\n zi2 = zi * zi,\r\n zr = zr2 - zi2 + cr,\r\n zi = temp + temp + ci,\r\n if [zi2 + zr2 > 16, return (i)],\r\n if [i > 1000, return (0)]\r\n }\r\n }";//字符串表达式
wchar_t myma