No speed gains from Cython

后端 未结 7 784
不思量自难忘°
不思量自难忘° 2021-01-30 14:05

I am trying to define a function that contains an inner loop for simulating an integral.

The problem is speed. Evaluating the function once can take up to 30 seconds on

7条回答
  •  难免孤独
    2021-01-30 14:40

    You could definitely speed up your code by using more of Numpy's capabilities.

    For instance:

    cdef np.ndarray[double, ndim=1] S = np.zeros(dtype = "d", shape = J)
    cdef int j
    for j in xrange(ns):
        S += P_i[:,j]
    

    would be much faster and legible as

    S = P_i.sum(axis=1)
    

    You also repeat some calculations, which thus take twice more time than necessary. For instance

    np.where(data[:,1]==(yr + 72))
    

    could be calculated only once and stored in a variable that you could reuse.

    You also perform a lot of reshaping and slicing: it could help to have your variables be in a simpler format from the beginning on. If possible, your code would be much clearer, and optimizations could be much more obvious.

提交回复
热议问题