Frage

I need to convert multiple char values to strings of corresponding ASCII characters as fast as possible. Here is a toy example. I want H() function, called from python environment, to return 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

I believe, this is not optimal variant, since it uses python function ord() which boxes 97 into python object, then returns char, boxes it into another python object str and finally converts it into c++ string. How could I do the conversion faster?

War es hilfreich?

Lösung

Found it!

<string>chr(i) 

may be replaced by

string(1, <char>i)

Here is an example of new variant:

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


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

New variant works 2 times faster.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top