Cython:将字符值转换为字符串的最快方法

Cython: Fastest way to convert char value to string

本文关键字:字符串 方法 转换 字符 Cython      更新时间:2023-10-16

我需要尽快将多个字符值转换为相应 ASCII 字符的字符串。这是一个玩具示例。我希望从python环境调用的H()函数返回str 'aaa'。

from libcpp.string cimport string
cdef string G():
   return chr(97)
def H():
    cdef string s
    s.append(G())
    s.append(G())
    s.append(G())
    return s

我相信,这不是最佳变体,因为它使用 python 函数 ord(),它将 97 框入 python 对象,然后返回 char,将其框入另一个 python 对象 str,最后将其转换为 c++ 字符串。如何更快地进行转换?

找到了!

<string>chr(i) 

可以替换为

string(1, <char>i)

以下是新变体的示例:

cdef string G():
    return string(1,<char>97)

def H():
    cdef string s
    s.append(G())
    s.append(G())
    s.append(G())
    return s

新变体的工作速度提高了 2 倍。