为了跟进我的评论,这里有3个选项(numpy和C和C ++标准库选项)
from libcpp.algorithm cimport sortfrom libc.stdlib cimport qsortimport numpy as npdef sort_numpy(double[:] a, kind): np.asarray(a).sort(kind=kind)# needs to be compiled with C++ def sort_cpp(double[::1] a): # a must be c continuous (enforced with [::1]) sort(&a[0], (&a[0]) + a.shape[0])# The C version requires a comparator function# which is a little slower since it requires calling function pointers# and passing pointers rather than numberscdef int cmp_func(const void* a, const void* b) nogil: cdef double a_v = (<double*>a)[0] cdef double b_v = (<double*>b)[0] if a_v < b_v: return -1 elif a_v == b_v: return 0 else: return 1def sort_c(double[:] a): # a needn't be C continuous because strides helps qsort(&a[0], a.shape[0], a.strides[0], &cmp_func)
结果将取决于您使用的C / C ++标准库,因此不要对我的结果了解太多。对于1000个长数组(排序5000次),我得到:
np quick: 0.11296762199890509np merge: 0.20624926299933577np heap: 0.2944786230000318c++: 0.12071316699984891c: 0.33728832399901876
即numpy版本最快。对于100个长数组,我得到
np quick: 0.022608489000049303np merge: 0.023513408999860985np heap: 0.024136934998750803c++: 0.008449130998997134c: 0.01909676999821386
即,如果您要对许多小数组进行排序,则调用numpy sort的开销很大,您应该使用C
++(或可能使用C)。如果要对大型数组进行排序,您可能会发现很难击败numpy。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)