Cython Speed Boost与可用性 [英] Cython Speed Boost vs. Usability

查看:92
本文介绍了Cython Speed Boost与可用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在寻找优化Python代码的方法时,我才遇到Cython。我阅读了Stack Overflow和python Wiki上的各种文章,并阅读了文章优化的一般规则。


Cython最吸引我的兴趣;您可以选择在Python代码本身中包含其他数据类型,而不用自己编写C代码。


这里是我尝试过的愚蠢测试,

 #!/ usr / bin / python 
#test.pyx
def test(值):
for xrange(value)中的i:
i ** 2
if(i == 1000000):
print i

test(10000001)

$ time python test.pyx

 真实0m16.774s 
用户0m16.745s
sys 0m0.024s

$时间cython test.pyx

 真实0m0.513s 
用户0m0.196s
sys 0m0.052s

现在,老实说,我很傻。我在这里使用的代码是纯python代码,而我更改的只是解释器。在这种情况下,如果cython很好,那么为什么人们仍然使用传统的Python解释器? Cython是否存在可靠性问题?

解决方案

其他答案已经说明了您是如何编译Cython代码而不执行的它。但是,我认为您可能想知道Cython可以使您的代码更快。当我编译代码时(尽管我是从其他模块运行该函数),使用 distutils ,与纯Python相比,我获得了非常小的速度提升-大约1%。但是,当我对您的代码进行一些小的更改时:

  def测试(长整型):
cdef long long i
cdef long long z
for i in xrange(value):
z = i ** 2
if(i == 1000000):
打印i如果z<
i:
打印是

并对其进行编译,我得到了以下时间: / p>


  • 纯Python代码: 20.4553578737秒

  • Cython代码: 0.199339860234秒



这是100倍加速。不太破旧。


I just came across Cython, while I was looking out for ways to optimize Python code. I read various posts on Stack Overflow, the python wiki and read the article "General Rules for Optimization".

Cython is something which grasps my interest the most; instead of writing C-code for yourself, you can choose to have other data types in your python code itself.

Here is a silly test I tried,

#!/usr/bin/python
# test.pyx
def test(value):
    for i in xrange(value):
    i**2
    if(i==1000000):
        print i

test(10000001)

$ time python test.pyx

real    0m16.774s 
user    0m16.745s
sys     0m0.024s

$ time cython test.pyx

real    0m0.513s 
user    0m0.196s 
sys     0m0.052s

Now, honestly, I'm dumbfounded. The code which I have used here is pure python code, and all I have changed is the interpreter. In this case, if the cython is this good, then why do people still use the traditional Python interpreter? Are there any reliability issues for Cython?

解决方案

The other answers have already explained how you were just compiling the Cython code, not executing it. However, I thought that you might want to know how much faster Cython can make your code. When I compiled the code you have (though I ran the function from from a different module) with distutils, I got very marginal speed gains over straight Python – about 1%. However, when I added a few small changes to your code:

def test(long long value):
    cdef long long i
    cdef long long z
    for i in xrange(value):
        z = i**2
        if(i==1000000):
            print i
        if z < i:
            print "yes"

and compiled it, I got the following times:

  • Pure Python code: 20.4553578737 seconds
  • Cython code: 0.199339860234 seconds

That’s a 100× speed-up. Not too shabby.

这篇关于Cython Speed Boost与可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆