最新消息:

几种Python C重构的性能差异

c admin 3244浏览 0评论

C重构,C重构,看的已经有点郁闷了!这次打算收尾了,将几种方法的性能做个横向比较吧,近期不再研究。

相关文章:

老一套的python源码:

def sheepBorn(i):
    if i < 1:
        return 0
    elif i < 2:
        return 1
    return sheepBorn(i-1) + sheepBorn(i-2) - sheepBorn(i-5)

和计时测试借口:

import time
from sheepBorn import sheepBorn

startTime = time.time()
print sheepBorn(32)
print time.time() - startTime

直接Python的测试结果耗时15.7993621826秒。

在不修改任何代码的情况下把它通过Cython编译为.so文件再测试一遍,

9.83871483803,有差距了!

修改为面向Cython优化过的pyx文件

def sheepBorn(int i):
    cdef int a
    if i < 1:
        a = 0
    elif i < 2:
        a = 1
    else:
        a = sheepBorn(i-1) + sheepBorn(i-2) - sheepBorn(i-5)

    return a

说实话,由于算法已经足够精简了,代码上几乎没有变化。
测试结果是7.72257995605,也就是一行的变动,导致了不错的提升!

Continue!

察看转换过程中的C中间文件,找到了 static PyObject *__pyx_pf_9sheepBorn_sheepBorn(PyObject *__pyx_self, PyObject *__pyx_arg_i)函数,很臃肿,简单的优化了一下:

static int py_sheepBorn(int i)
{
     if (i &lt 1) return 0;
     if (i &lt 2) return 1;
     return py_sheepBorn(i -1) + py_sheepBorn(i-2) - py_sheepBorn(i-5);
}
//修改部分略过

重新编译为python 的 so扩展
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c sheepBorn.c -o build/temp.linux-x86_64-2.7/sheepBorn.o
gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions build/temp.linux-x86_64-2.7/sheepBorn.o -o /root/ctype/cython/sheepBorn.so
测试结果0.174817800522,这是极限吗?

 

转载请注明:爱开源 » 几种Python C重构的性能差异

您必须 登录 才能发表评论!