在Cython中优化字符串

Pau*_*son 10 python string optimization performance cython

我试图向我们的小组展示Cython的优点,以提高Python的性能.我已经展示了几个基准测试,所有测试都只是通过以下方式加速:

  1. 编译现有的Python代码.
  2. 使用cdef到静态类型变量,特别是在内部循环中.

但是,我们的许多代码都进行了字符串操作,而且我无法通过键入Python字符串来提供优化代码的好例子.

我试过的一个例子是:

cdef str a
cdef int i,j
for j in range(1000000):
   a = str([chr(i) for i in range(127)])
Run Code Online (Sandbox Code Playgroud)

但是输入'a'作为字符串实际上会使代码运行得更慢.我已经阅读了关于'Unicode和传递字符串'的文档,但是在我展示的情况下,我对它是如何应用感到困惑.我们不使用Unicode - 一切都是纯ASCII.我们使用的是Python 2.7.2

任何建议表示赞赏.

Vee*_*rac 13

我建议你在cpython.array.arrays 上做你的操作.最好的文档是C API和Cython源代码(参见此处).

from cpython cimport array

def cfuncA():
    cdef str a
    cdef int i,j
    for j in range(1000):
        a = ''.join([chr(i) for i in range(127)])

def cfuncB():
    cdef:
        str a
        array.array[char] arr, template = array.array('c')
        int i, j

    for j in range(1000):
        arr = array.clone(template, 127, False)

        for i in range(127):
            arr[i] = i

        a = arr.tostring()
Run Code Online (Sandbox Code Playgroud)

请注意,所需的操作会因您对字符串的操作而有很大差异.

>>> python2 -m timeit -s "import pyximport; pyximport.install(); import cyytn" "cyytn.cfuncA()"
100 loops, best of 3: 14.3 msec per loop

>>> python2 -m timeit -s "import pyximport; pyximport.install(); import cyytn" "cyytn.cfuncB()"
1000 loops, best of 3: 512 usec per loop
Run Code Online (Sandbox Code Playgroud)

在这种情况下,这是一个30倍的加速.


此外,FWIW,您可以通过更换脱下另一公平几微秒arr.tostring()arr.data.as_chars[:len(arr)]和打字abytes.