码迷,mamicode.com
首页 > 编程语言 > 详细

Perl, Python, Erlang, C语言运行速度的比较

时间:2014-10-29 02:12:47      阅读:1058      评论:0      收藏:0      [点我收藏+]

标签:style   http   io   color   os   ar   for   sp   on   

主要是通过 蒙特卡罗法来计算圆周率。代码如下:
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秒左右:
bubuko.com,布布扣

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 , " time = ", (endtime - starttime).seconds

Python运行结果如下,2千万次平均执行时间是30秒左右:
bubuko.com,布布扣

3) pi.erl

-module(pi).
-export([pi/1]).

pi(N) ->
  pi(N, N, 0).
  
pi(N, 0, 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, I - 1, Total) 
  end.

Erlang运行如下,2千万次平均执行时间是30秒左右:
bubuko.com,布布扣

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 ,pi, elapsed_time);   
}



C运行如下, 2千万次平均执行时间是3秒左右:

bubuko.com,布布扣

Python, Erlang 速度相当, Perl稍微快一丁点, C语言是它们的10倍。


Perl, Python, Erlang, C语言运行速度的比较

标签:style   http   io   color   os   ar   for   sp   on   

原文地址:http://my.oschina.net/huanghongqiao/blog/338351

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!