o{"结果=",k,", 时间=",[clock()-t]/1000.,"秒。\r\n"}
};
Lu运行结果:
结果=200000010000000, 时间=7.922秒。
在该例子中,Lu的速度为VC的7.922/0.125=63.376分之一。注意循环次数都增加到了20000000次。
8 一段有趣的程序
在这个网页看到一篇各种语言运行速度比较的文章,摘抄如下:
— Erik Wrenholt (erik -at- timestretch.com) 2005-09-20
Language Time Relative Speed
C gcc-4.0.1 0.05 seconds 1.00 x
ocaml compiled 3.09.2 0.05 seconds 1.00 x
SBCL 1.0.2 0.13 seconds 2.55 x
Java 1.4.2 0.40 seconds 8.00 x
Io 20070410 Vector 1.40 seconds 28.09 x
Lua 5.1 1.50 seconds 30.00 x
ocaml bytecode 3.09.2 3.76 seconds 75.15 x
Python 2.5.1 9.99 seconds 199.80 x
Ghostscript 8.51 11.66 seconds 233.12 x
Perl 5.8.6 Optimized 12.37 seconds 247.34 x
TCL 8.4 Optimized 16.00 seconds 320.00 x
Perl 5.8.6 21.75 seconds 435.00 x
PHP 5.1.4 23.12 seconds 462.40 x
java script SpiderMonkey v1.6 31.06 seconds 621.27 x
Ruby 1.8.4 34.31 seconds 686.18 x
Emacs Lisp 47.25 seconds 945.00 x
Applescript 71.75 seconds 1435.00 x
Io 20070410 85.26 seconds 1705.13 x
用以上网址提供的c代码与Lu比较,c代码改写为vs 2008可接受的形式,编译运行,结果如下:
#include "stdafx.h"
#include
#include
#define BAILOUT 16
#define MAX_ITERATIONS 1000
int mandelbrot(double x, double y)
{
double cr = y - 0.5;
double ci = x;
double zi = 0.0;
double zr = 0.0;
int i = 0;
while(1) {
i ++;
double temp = zr * zi;
double zr2 = zr * zr;
double zi2 = zi * zi;
zr = zr2 - zi2 + cr;
zi = temp + temp + ci;
if (zi2 + zr2 > BAILOUT)
return i;
if (i > MAX_ITERATIONS)
return 0;
}
}
int _tmain (int argc, _TCHAR* argv[]) {
clock_t old,now;
old=clock();
int x,y;
for (y = -39; y < 39; y++) {
printf("\n");
for (x = -39; x < 39; x++) {
int i = mandelbrot(x/40.0, y/40.0);
if (i==0)
printf("*");
else
printf(" ");
}
}
printf ("\n");
now=clock();
double query_time = ((double)(now-old))/CLOCKS_PER_SEC;
printf ("C Elapsed %0.2f\n", query_time);
return 0;
}
运行结果:
*
*
*
*
*
***
*****
*****
***
*
*********
*************
***************
*********************
*********************
*******************
*******************
*******************
*******************
***********************
*******************
*******************
*********************
*******************
*******************
*****************
***************
*************