NumPy ndarray.all() vs np.all(ndarray) vs all(ndarray) [英] NumPy ndarray.all() vs np.all(ndarray) vs all(ndarray)
问题描述
Python/NumPy 中的三个all"方法有什么区别?性能差异的原因是什么?ndarray.all() 真的是三个中最快的吗?
What is the the difference between the three "all" methods in Python/NumPy? What is the reason for the performance difference? Is it true that ndarray.all() is always the fastest of the three?
这是我运行的计时测试:
Here is a timing test that I ran:
In [59]: a = np.full(100000, True, dtype=bool)
In [60]: timeit a.all()
The slowest run took 5.40 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.24 µs per loop
In [61]: timeit all(a)
1000 loops, best of 3: 1.34 ms per loop
In [62]: timeit np.all(a)
The slowest run took 5.54 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 6.41 µs per loop
推荐答案
np.all(a)
和 a.all()
的区别很简单:
The difference between np.all(a)
and a.all()
is simple:
- 如果
a
是numpy.array
那么np.all()
将简单地调用a.all()代码>.
- 如果
a
不是numpy.array
,np.all()
调用会将其转换为numpy.array
然后调用a.all()
.a.all()
另一方面会失败,因为a
不是numpy.array
,因此可能没有all
方法.
- If
a
is anumpy.array
thennp.all()
will simply calla.all()
. - If
a
is not anumpy.array
thenp.all()
call will convert it to annumpy.array
and then calla.all()
.a.all()
on the other hand will fail becausea
wasn't anumpy.array
and therefore probably has noall
method.
np.all
和 all
的区别比较复杂.
The difference between np.all
and all
is more complicated.
all
函数适用于任何可迭代对象(包括list
、set
s、generators
、...).np.all
仅适用于numpy.array
s(包括所有可以转换为 numpy 数组的东西,即list
s 和元组
s).np.all
处理具有指定数据类型的array
,这使得在比较!= 0
时非常有效.all
但是需要为每个项目评估bool
,这要慢得多.- 使用 python 函数处理数组非常慢,因为数组中的每个项目都需要转换为 python 对象.
np.all
不需要进行这种转换.
- The
all
function works on any iterable (includinglist
,set
s,generators
, ...).np.all
works only fornumpy.array
s (including everything that can be converted to a numpy array, i.e.list
s andtuple
s). np.all
processes anarray
with specified data type, that makes it pretty efficient when comparing for!= 0
.all
however needs to evaluatebool
for each item, that's much slower.- processing arrays with python functions is pretty slow because each item in the array needs to be converted to a python object.
np.all
doesn't need to do that conversion.
请注意,时间还取决于您的 a
的类型.如果您处理 python 列表 all
可以更快地处理相对较短的列表.如果你处理一个数组,np.all
和 a.all()
在几乎所有情况下都会更快(除了 object
数组,但我不会走那条路,那是疯子).
Note that the timings depend also on the type of your a
. If you process a python list all
can be faster for relativly short lists. If you process an array, np.all
and a.all()
will be faster in almost all cases (except maybe for object
arrays, but I won't go down that path, that way lies madness).
这篇关于NumPy ndarray.all() vs np.all(ndarray) vs all(ndarray)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!