我怎样才能使这个Cython扩展更快?

2024-04-23 08:14:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的第一个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)])

谢谢!在


Tags: ofthetobytesbufferarrayusedint
1条回答
网友
1楼 · 发布于 2024-04-23 08:14:54

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

bytes_string = chr[:23]

或者更广泛地说:

^{pr2}$

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

相关问题 更多 >