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