无法让 cython 循环比 pyhton 循环运行得更快

问题描述 投票:0回答:0

我正在尝试使用 cython 来加速 python 函数,但到目前为止还没有运气。原始的 python 代码目前更快。如果有人对如何降低执行时间有任何想法,我们将不胜感激。

原始的python代码。
slave_range_function.py:

import numpy as np

def slave_range(i0:np.array,i1:np.array,slave_shear:np.array):
    n=len(i0)
    shear_range =np.zeros(n)
    for i in range(n):
        i0_ = i0[i]
        i1_ = i1[i]
        sub_array = slave_shear[i0_:i1_]
        max_sub = sub_array.max()
        min_sub = sub_array.min()
        shear_range[i] = max_sub-min_sub
    return shear_range

cython代码:
slave_range_cy.pyx:

import numpy as np
cimport numpy as np
np.import_array()

INT_TYPE = np.int32
FLOAT_TYPE = np.float64

ctypedef np.int32_t INT_TYPE_t
ctypedef np.float64_t FLOAT_TYPE_t


def slave_range(np.ndarray[INT_TYPE_t, ndim=1] i0,np.ndarray[INT_TYPE_t, ndim=1] i1,
    np.ndarray[FLOAT_TYPE_t, ndim=1] slave_shear):
    cdef int n = i0.shape[0]
    cdef np.ndarray shear_range = np.zeros(n,dtype = FLOAT_TYPE)
    cdef int i0_
    cdef int i1_
    cdef FLOAT_TYPE_t max_sub
    cdef FLOAT_TYPE_t min_sub

    for i in range(n):
        i0_ = i0[i]
        i1_ = i1[i]
        max_sub = np.max(slave_shear[i0_:i1_])
        min_sub = np.max(slave_shear[i0_:i1_])
        shear_range[i] = max_sub-min_sub
    return shear_range

编译cython代码的设置文件:

from distutils.core import setup
from Cython.Build import cythonize
import numpy

setup(ext_modules=cythonize("slave_range_cy.pyx"),
      include_dirs=[numpy.get_include()])
python cython
© www.soinside.com 2019 - 2024. All rights reserved.