似乎有一个共同的观点,即使用np.take
比数组索引要快得多。例如http://wesmckinney.com/blog/numpy-indexing-peculiarities/,Fast numpy fancy indexing和Fast(er) numpy fancy indexing and reduction?。还有人建议np.ix_
在某些情况下更好。
我已经完成了一些分析,在大多数情况下似乎确实如此,尽管随着数组变大,差异会减小。 性能受到数组大小,索引长度(行数)和列数的影响。行数似乎具有最大的影响,即使索引是1D,数组中的列数也会产生影响。更改索引的大小似乎不会影响方法之间的内容。
所以,问题有两个:1。为什么方法之间的性能差异如此之大? 2.什么时候使用一种方法而不是另一种方法?是否有一些数组类型,排序或形状总能更好地工作?
有很多东西可能影响性能,所以我在下面展示了其中的一些,并包含了用于尝试使其可重现的代码。
编辑我已经更新了图上的y轴以显示完整的值范围。它更清楚地表明差异小于1D数据的差异。
查看与行数相比的运行时间表明索引非常一致,略有上升趋势。随着行数增加,take
持续变慢。
随着列数增加都变慢,但take
有更高的增长(这仍然是一维指数)。
与2D数据结果相似。还展示了使用ix_
,它似乎总体上表现最差。
from pylab import *
import timeit
def get_test(M, T, C):
"""
Returns an array and random sorted index into rows
M : number of rows
T : rows to take
C : number of columns
"""
arr = randn(M, C)
idx = sort(randint(0, M, T))
return arr, idx
def draw_time(call, N=10, V='M', T=1000, M=5000, C=300, **kwargs):
"""
call : function to do indexing, accepts (arr, idx)
N : number of times to run timeit
V : string indicating to evaluate number of rows (M) or rows taken (T), or columns created(C)
** kwargs : passed to plot
"""
pts = {
'M': [10, 20, 50, 100, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, ],
'T': [10, 50, 100, 500, 1000, 5000, 10000, 50000],
'C': [5, 10, 20, 50, 100, 200, 500, 1000],
}
res = []
kw = dict(T=T, M=M, C=C) ## Default values
for v in pts[V]:
kw[V] = v
try:
arr, idx = get_test(**kw)
except CallerError:
res.append(None)
else:
res.append(timeit.timeit(lambda :call(arr, idx), number=N))
plot(pts[V], res, marker='x', **kwargs)
xscale('log')
ylabel('runtime [s]')
if V == 'M':
xlabel('size of array [rows]')
elif V == 'T':
xlabel('number of rows taken')
elif V == 'C':
xlabel('number of columns created')
funcs1D = {
'fancy':lambda arr, idx: arr[idx],
'take':lambda arr, idx: arr.take(idx, axis=0),
}
cidx = r_[1, 3, 7, 15, 29]
funcs2D = {
'fancy2D':lambda arr, idx: arr[idx.reshape(-1, 1), cidx],
'take2D':lambda arr, idx: arr.take(idx.reshape(-1, 1)*arr.shape[1] + cidx),
'ix_':lambda arr, idx: arr[ix_(idx, cidx)],
}
def test(funcs, N=100, **kwargs):
for descr, f in funcs.items():
draw_time(f, label="{}".format(descr), N=100, **kwargs)
legend()
figure()
title('1D index, 30 columns in data')
test(funcs1D, V='M')
ylim(0, 0.25)
# savefig('perf_1D_arraysize', C=30)
figure()
title('1D index, 5000 rows in data')
test(funcs1D, V='C', M=5000)
ylim(0, 0.07)
# savefig('perf_1D_numbercolumns')
figure()
title('2D index, 300 columns in data')
test(funcs2D, V='M')
ylim(0, 0.01)
# savefig('perf_2D_arraysize')
figure()
title('2D index, 30 columns in data')
test(funcs2D, V='M')
ylim(0, 0.01)
# savefig('perf_2D_arraysize_C30', C=30)
答案是非常低级的,并且与C编译器和CPU缓存优化有关。请参阅本次numpy issue与Sebastian Berg和Max Bolingbroke(两位numpy的贡献者)的积极讨论。
花哨的索引试图对于如何读取和写入内存(C顺序与F顺序)“智能”,而.take
将始终保持C顺序。这意味着对于F排序的数组,花式索引通常要快得多,并且在任何情况下对于大型数组应该总是更快。现在,numpy在不考虑阵列大小或运行的特定硬件的情况下决定什么是“智能”方式。因此,对于较小的阵列,由于更好地使用CPU缓存中的读取,因此选择“错误的”内存顺序实际上可能会获得更好的性能。