龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > python编程 >

深入理解Python 代码优化详解(8)

时间:2014-10-28 02:27来源:网络整理 作者:网络 点击:
分享到:
复制代码 代码如下: from time import time def test(int n): cdef int a =0 cdef int i for i in xrange(n): a+= i return a t = time() test(10000000) print "total run time:" print time()-t 测试结果

复制代码 代码如下:

from time import time
 def test(int n):
        cdef int a =0
        cdef int i
        for i in xrange(n):
                a+= i
        return a
 t = time()
 test(10000000)
 print "total run time:"
 print time()-t

  测试结果:

复制代码 代码如下:

[GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import pyximport; pyximport.install()
 >>> import ctest
 total run time:
 0.00714015960693

  清单 10. Python 测试代码

复制代码 代码如下:

from time import time
 def test(n):
        a =0;
        for i in xrange(n):
                a+= i
        return a
 t = time()
 test(10000000)
 print "total run time:"
 print time()-t
 [root@v5254085f259 test]# python test.py
 total run time:
 0.971596002579

  从上述对比可以看到使用 Cython 的速度提高了将近 100 多倍。

总结
 
  本文初步探讨了 python 常见的性能优化技巧以及如何借助工具来定位和分析程序的性能瓶颈,并提供了相关可以进行性能优化的工具或语言,希望能够更相关人员一些参考。

精彩图集

赞助商链接