Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top