gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:39:50 25 4
gpt4 key购买 nike

我需要尽快将多个 char 值转换为相应 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 倍。

关于python - Cython:将字符值转换为字符串的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21791566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com