首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

你敢跑这段Python脚本吗?解决方法

2012-02-29 
你敢跑这段Python脚本吗?哈哈,有点开玩笑的意思了。不过让我有机会了解了Python的效率。我的机器配置为P4 3.

你敢跑这段Python脚本吗?
哈哈,有点开玩笑的意思了。
不过让我有机会了解了Python的效率。我的机器配置为P4 3.0G、Memory为1.5G DDR400。

Python code
import timeimport math#import psycodef test():    t=time.time()    for j in range(100000000):        s=math.sqrt(j)    print 'Using',time.time() - t,'seconds!'#test = psyco.proxy(test)test()


当我去掉注释后,运行时间为13.3370001316秒。(用psyco优化后是狂耗CPU,优化前是狂占内存,由此优化的意义可见一斑)

同样的内容:
C/C++ code
#include <iostream>#include <cmath>#include <ctime>int main(){    using namespace std;    clock_t start = clock();    for(int i=0; i < 100000000; ++i) double s=sqrt(static_cast<double>(i));    clock_t finish = clock();    cout << "using " << (double)(finish - start) / CLOCKS_PER_SEC << " seconds!\n";    return 0;}


VC2008下面,Debug运行时间为2.364秒,Release为0秒(因为时间靠得太近了)。

最后,上面那段Python代码不去掉注释的时间,只有您自己知道了。

谁能把这Python代码让我运行到5秒以内,分就给谁啦。

[解决办法]
delphi版本的居然跑了1.23秒

program test;
{$apptype console}
uses
system,sysutils,dateutils;
var
r:double;
i:longint;
t_start:tdatetime;
begin
t_start := Now();
for i:=0 to 100000000-1 do
r := sqrt(i);
writeln(MilliSecondsBetween(Now() , t_start)/1000);
end.
[解决办法]
你range 换成xrange 基本上60秒而已。
[解决办法]
将代码中的for循环改为foreach,速度会提高6~7秒钟。
Perl code
use strict;use warnings;sub test{    my $t=time();    my $i=0;    my $s;    foreach $i (1..100000000)    {        $s=sqrt($i);    }    print('Using ',time() - $t,' seconds!');}test(); 

热点排行