我正在尝试使用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.
为什么加速比这么低?有什么办法可以增加这个比例呢?在
您正在为每一行创建一个
date
对象。这需要更多的时间,既因为您必须分配和释放内存,也因为它会对参数运行各种检查以确保它是有效的日期。在为了更快地进行比较,可以使用整数比较比较来比较
np.datetime64
数组,或者将年、月和日列分别作为整数进行比较。在相关问题 更多 >
编程相关推荐