python比c语言开发速度快多少倍_Perl, Python, Erlang, C语言运行速度的比较

主要是通过 蒙特卡罗法来计算圆周率。代码如下:

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秒左右:

011224_mhD2_214112.jpg

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秒左右:

011528_84yF_214112.jpg

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秒左右:

011754_Ftgl_214112.jpg

4) pi.c

#include

#include

#include

#include

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秒左右:

012019_lvlJ_214112.jpg

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值