主要是通过 蒙特卡罗法来计算圆周率。代码如下:
1) pi.pl:
$time1 = time(); foreach (1..20000000) { my($x,$y) = (rand(),rand()); if(sqrt($x ** 2 + $y ** 2) < 1) { $total += 1; } } $pi = 4.0 * $total / 20000000; $time2 = time(); print "Pi = ",$pi," time = ",$time2 - $time1;
Perl脚本运行结果如下,2千万次平均执行时间是27秒左右:
2)pi.py
import random import datetime import math starttime = datetime.datetime.now() total = 0 for i in xrange(20000000): x,y = random.random(),random.random() if math.sqrt(x ** 2 + y ** 2) < 1: total += 1 pi = 4.0 * total / 20000000 endtime = datetime.datetime.now() print "pi = ",pi,(endtime - starttime).seconds
Python运行结果如下,2千万次平均执行时间是30秒左右:
3) pi.erl
-module(pi). -export([pi/1]). pi(N) -> pi(N,N,0). pi(N,Total) -> 4.0 * Total / N; pi(N,I,Total) -> X = random:uniform(),Y = random:uniform(),R = math:sqrt(X * X + Y * Y),if R < 1 -> pi(N,I - 1,Total + 1); true -> pi(N,Total) end.
Erlang运行如下,2千万次平均执行时间是30秒左右:
4) pi.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> int main() { time_t start_time,end_time; double elapsed_time; double x,y,pi; long i,total; total = 0; srand((unsigned)time(0)); time(&start_time); for(i = 0 ; i < 20000000; i ++ ) { x = rand() / (double)(RAND_MAX); y = rand() / (double)(RAND_MAX); if (sqrt(x * x + y * y) < 1) { total += 1; } } pi = 4.0 * total / 20000000; time(&end_time); elapsed_time = difftime(end_time,start_time); printf(" total = %d,pi = %f,time = %f",total,elapsed_time); }
Python,Erlang 速度相当, Perl稍微快一丁点, C语言是它们的10倍。