9

cythonを使用して次のコードを高速化したい:

class A(object):
    cdef fun(self):
        return 3


class B(object):
    cdef fun(self):
        return 2

def test():
    cdef int x, y, i, s = 0
    a = [ [A(), B()], [B(), A()]]
    for i in xrange(1000):
        for x in xrange(2):
            for y in xrange(2):
                s += a[x][y].fun()
    return s

頭に浮かぶのは次のようなものだけです。

def test():
    cdef int x, y, i, s = 0
    types = [ [0, 1], [1, 0]]
    data = [[...], [...]]
    for i in xrange(1000):
        for x in xrange(2):
            for y in xrange(2):
                if types[x,y] == 0:
                   s+= A(data[x,y]).fun()
                else:
                   s+= B(data[x,y]).fun() 
    return s

基本的に、C ++での解決策は、仮想メソッドを使用していくつかの基本クラスへのポインターの配列をfun()作成することです。そうすれば、かなりすばやく反復処理できます。Python / Cythonを使用してそれを行う方法はありますか?

ところで:Pythonリストの代わりにdtype = object_でnumpyの2D配列を使用する方が速いでしょうか?

4

1 に答える 1

7

このようなコードは約20倍のスピードアップを与えるように見えます:

import numpy as np
cimport numpy as np
cdef class Base(object):
    cdef int fun(self):
        return -1

cdef class A(Base):
    cdef int fun(self):
        return 3


cdef class B(Base):
    cdef int fun(self):
        return 2

def test():
    bbb = np.array([[A(), B()], [B(), A()]], dtype=np.object_)
    cdef np.ndarray[dtype=object, ndim=2] a = bbb

    cdef int i, x, y
    cdef int s = 0
    cdef Base u

    for i in xrange(1000):
        for x in xrange(2):
            for y in xrange(2):
                u = a[x,y]                
                s += u.fun()
    return s

AとBがBaseから継承されていることも確認します。おそらく、リリースビルドで無効にして、さらに高速化する方法があります。

編集:チェックはを使用して削除できます

u = <Base>a[x,y]
于 2010-10-22T14:35:40.443 に答える