如何让Cython Extension更快?

时间:2012-09-17 08:53:57

标签: python optimization cython pyrex

这是我的第一个cython(pyx)模块。我怎样才能让它更快?具体来说,我正在寻找最后一行的帮助。它编译并运行,但我担心它会转换为Py *对象的东西,这可能会更快。

此外,如果您发现任何明显错误,请告诉我们!

ctypedef unsigned short UInt8

DEF BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

def encode_16_bytes(char *thebytes):
    cdef UInt8 *b      # the bytes cast to an array of UInt8
    cdef int i         # used to assign a value to the buffer
    cdef int j         # used to count up through the bytes
    cdef char buf[23]  # the resulting buffer of characters

    # initialize variables
    for i in range(23): # set buf array to zeros
        buf[i] = '\0'
    b = <UInt8 *>thebytes
    i = 0
    j = 1

    i += 1
    buf[i] = BASE64[(b[0] >> 6) & 0x3F]
    i += 1
    buf[i] = BASE64[b[0] & 0x3F]

    # iterate through the bytes 4 words at a time, setting each byte to its
    # mapped BASE64 counterpart
    while j < 16:
        i += 1
        buf[i] = BASE64[(b[j] >> 2) & 0x3F]
        i += 1
        buf[i] = BASE64[((b[j] << 4) | (b[j + 1] >> 4)) & 0x3F]
        i += 1
        buf[i] = BASE64[((b[j + 1] << 2) | (b[j + 2] >> 6)) & 0x3F]
        i += 1
        buf[i] = BASE64[b[j + 2] & 0x3F]
        j += 3

    # join up the characters into a string
    return "".join([chr(buf[i]) for i in range(23)])

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以通过将“.join(...)替换为以下内容,从C char缓冲区中创建Python字节字符串:

bytes_string = chr[:23]

或更一般地说:

bytes_string = chr[:buffer_length]

See here以供参考和更多示例。