我有一个包含10 ^ 8个浮点数的numpy数组,想要计算它们中有多少> =给定的阈值。速度至关重要,因为操作必须在大量此类阵列上完成。参赛者到目前为止
np.sum(myarray >= thresh)
np.size(np.where(np.reshape(myarray,-1) >= thresh))
Count all values in a matrix greater than a value的答案表明np.where()会更快,但我发现时序结果不一致。我的意思是一些实现和布尔条件np.size(np.where(cond))比np.sum(cond)更快,但对于某些人来说它更慢。
具体来说,如果大部分条目满足条件,那么np.sum(cond)明显更快但如果一小部分(可能小于十分之一)那么np.size(np.where(cond))获胜。
问题分为两部分:
答案 0 :(得分:2)
使用cython可能是一个不错的选择。
import numpy as np
cimport numpy as np
cimport cython
from cython.parallel import prange
DTYPE_f64 = np.float64
ctypedef np.float64_t DTYPE_f64_t
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
cdef int count_above_cython(DTYPE_f64_t [:] arr_view, DTYPE_f64_t thresh) nogil:
cdef int length, i, total
total = 0
length = arr_view.shape[0]
for i in prange(length):
if arr_view[i] >= thresh:
total += 1
return total
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
def count_above(np.ndarray arr, DTYPE_f64_t thresh):
cdef DTYPE_f64_t [:] arr_view = arr.ravel()
cdef int total
with nogil:
total = count_above_cython(arr_view, thresh)
return total
不同提议方法的时间安排。
myarr = np.random.random((1000,1000))
thresh = 0.33
In [6]: %timeit count_above(myarr, thresh)
1000 loops, best of 3: 693 µs per loop
In [9]: %timeit np.count_nonzero(myarr >= thresh)
100 loops, best of 3: 4.45 ms per loop
In [11]: %timeit np.sum(myarr >= thresh)
100 loops, best of 3: 4.86 ms per loop
In [12]: %timeit np.size(np.where(np.reshape(myarr,-1) >= thresh))
10 loops, best of 3: 61.6 ms per loop
使用更大的数组:
In [13]: myarr = np.random.random(10**8)
In [14]: %timeit count_above(myarr, thresh)
10 loops, best of 3: 63.4 ms per loop
In [15]: %timeit np.count_nonzero(myarr >= thresh)
1 loops, best of 3: 473 ms per loop
In [16]: %timeit np.sum(myarr >= thresh)
1 loops, best of 3: 511 ms per loop
In [17]: %timeit np.size(np.where(np.reshape(myarr,-1) >= thresh))
1 loops, best of 3: 6.07 s per loop