加速与Cython的日期时间比较

2024-04-30 05:05:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Cython来加速datetime之间的比较,当传递一个numpy数组时(或者足够创建datetime的细节)。首先,我试着看看Cython如何加快整数之间的比较。在

testArrayInt = np.load("testArray.npy")

Python方法:

^{pr2}$

赛顿法:

def processInt(np.ndarray[np.int_t,ndim=1] array):
    cdef int rows = array.shape[0]
    cdef int counter = 0
    cdef int compareSuccess = 0
    for counter in range(rows):
        if testInt > array[counter]:
            compareSuccess = compareSuccess+1
    print compareSuccess

与1000000行的numpy数组的时间比较是:

Python: 0.204969 seconds
Cython: 0.000826 seconds
Speedup: 250 times approx.

用datetimes重复相同的练习: 因为cython不接受datetime数组,所以我将一个包含year、month和days的数组拆分并发送给这两个方法。在

testArrayDateTime = np.load("testArrayDateTime.npy")

Python代码:

def processDateTime(array):
    compareSuccess = 0
    d = datetime(2009,1,1)#test datetime used to compare
    rows = array.shape[0]
    for counter in range(rows):
        dTest = datetime(array[counter][0],array[counter][1],array[counter][2])
        if d>dTest:
            compareSuccess+=1
    print compareSuccess

赛顿代码:

from cpython.datetime cimport date

def processDateTime(np.ndarray[np.int_t, ndim=2] array):
    cdef int compareSuccess = 0
    cdef int rows = avlDates.shape[0]
    cdef int counter = 0
    for counter in range(rows):
        dTest = date(array[counter,0],array[counter,1],array[counter,2])
        if dTest>d:
            compareSuccess=compareSuccess+1
    print compareSuccess

性能:

Python: 0.865261 seconds
Cython: 0.162297 seconds
Speedup: 5 times approx. 

为什么加速比这么低?有什么办法可以增加这个比例呢?在


Tags: fordatetimedefnpcounter数组arraycython
1条回答
网友
1楼 · 发布于 2024-04-30 05:05:17

您正在为每一行创建一个date对象。这需要更多的时间,既因为您必须分配和释放内存,也因为它会对参数运行各种检查以确保它是有效的日期。在

为了更快地进行比较,可以使用整数比较比较来比较np.datetime64数组,或者将年、月和日列分别作为整数进行比较。在

相关问题 更多 >