zoukankan      html  css  js  c++  java
  • 数学之路-python计算实战(2)-初遇pypy

    PyPy是Python开发人员为了更好的Hack Python创建的项目。此外,PyPy比CPython是更加灵活,易于使用和试验,以制定详细的功能在不同情况的实现方法,能够非常easy实施。 该项目的目标是,让PyPy比C实现的Python更为easy的适应各个项目和方便裁剪。

    PyPy的第一部分:用Python实现的Python

    事实上这么说并不准确,准确得说应该是用rPython实现的Python。rPython是Python的一个子集,尽管rPython不是完整的Python,但用rPython写的这个Python实现却是能够解释完整的Python语言。

    PyPy的第二部分:编译器

    这是一个编译rPython的编译器,或者说这个编译器有一个rPython的前端。眼下也仅仅有这么一个前端。只是它的后端却是不少。也就是说这个编译器支持很多的目标语言,比較重要的有:C。CIL。Javascript ...


    PyPy还提供了JIT编译器和沙盒功能。因此执行速度比CPython要快。以及能够安全的执行一些不被信任的代码。

    PyPy另一个单独的支持微线程的版本号。这些都是python的弱项,pypy是神器

    下面面程序为例:

    import  time
    start=time.clock()
    sum=0
    i=1.0
    while (i<10000000):
        sum+=i/2.22
        i=i+1
    print "sum:%f"%sum
    end = time.clock()
    print "seconds:%f"%sum

    本博客全部内容是原创。假设转载请注明来源

    http://blog.csdn.net/myhaspl/



    执行上面程序

    deep@myddb:~$ python pythontest.py
    sum:22522520270270.273438
    seconds:4.090000
    deep@myddb:~$ ./pypy  pythontest.py
    sum:22522520270270.273438
    seconds:0.256000
    deep@myddb:~$ 

    效果非常不错,让人惊讶

    上面程序用到下面函数:

    time.clock()

    On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.


    Python的标准库手冊推荐在不论什么系统下都尽量使用time.clock()。

    只是要注意是在win32系统下,这个函数返回的是真实时间(wall_time),而在Unix/Linux下返回的是CPU时间,不包含其它程序使用的CPU时间。


    只是与C还是有差距的,可是已经非常不错的。相比cpython来说。

    deep@myddb:~$ gcc pythontest.c -o test1
    deep@myddb:~$ ./test1
    sum = 22522520270270.273438
    seconds = 0.080000  s
    deep@myddb:~$ ./pypy  pythontest.py
    sum:22522520270270.273438
    seconds:0.236000
    deep@myddb:~$ 


    pythontest.c程序例如以下:

    #include <TIME.H>
    #include <STDIO.H>


    int main(){
    long Time_Start = 0,Time_End = 0;
    double Time_Total = 0.0;


    double i = 1.0;
    double sum = 0.0;


    Time_Start = clock();
    while(i<10000000){
    sum += (double)i/2.22;
    i = i+1;
    }
    Time_End = clock();


    Time_Total = (double)(Time_End-Time_Start)/CLOCKS_PER_SEC;
    printf("sum = %f ",sum);
    printf("seconds = %f  s ",Time_Total);
    return 0;
    }

  • 相关阅读:
    poj 1743 Musical Theme 后缀数组
    poj 1743 Musical Theme 后缀数组
    cf 432D Prefixes and Suffixes kmp
    cf 432D Prefixes and Suffixes kmp
    hdu Data Structure? 线段树
    关于position和anchorPoint之间的关系
    ios POST 信息
    CALayers的代码示例
    CALayers详解
    ios中得sqlite使用基础
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5141243.html
Copyright © 2011-2022 走看看