簡體   English   中英

Cython:將char值轉換為字符串的最快方法

[英]Cython: Fastest way to convert char value to string

我需要盡快將多個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倍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM