np.empty与np.zeros的速度 [英] Speed of np.empty vs np.zeros
问题描述
我正在使用numpy版本1.14.3和python 2.7.12.
I am using numpy version 1.14.3 and python 2.7.12.
引用这个问题,我正在寻找使用np.zeros和np.empty初始化数组之间的速度差别很大.但是,输出是相同的.
Referencing this question, I am finding dramatically different speeds between initializing arrays with np.zeros and np.empty. However, the output is the same.
import numpy as np
r = np.random.random((50, 100, 100))
z = np.zeros(r.shape)
e = np.empty(r.shape)
np.allclose(e, z)
这将返回True
.但是,计时功能%timeit
给出了截然不同的结果:
This returns True
. However, the timing functions %timeit
gives very different results:
%timeit z = np.zeros(r.shape)
10000次循环,最佳3:每个循环143 µs
10000 loops, best of 3: 143 µs per loop
%timeit e = np.empty(r.shape)
1000000次循环,最好为3次:每个循环1.83 µs
1000000 loops, best of 3: 1.83 µs per loop
上面引用的先前接受的答案表明,np.zeros
始终是更好的选择,并且它也更快.
The previously accepted answer referenced above says that np.zeros
was always the better choice, and that it is faster too.
为什么不使用np.empty的速度是np.zeros的80倍并返回相同的答案?
修改
正如user2285236所指出的,翻转初始化z
和e
的顺序将破坏相等性,因为它会覆盖同一内存区域.
Edit
As user2285236 pointed out, flipping the order of initializing z
and e
will break the equality, because it overwrites on the same memory area.
推荐答案
np.empty
和np.zeros
做不同的事情.
np.empty
从可用的内存空间创建一个数组,将所有碰巧挂在内存中的值保留为这些值. 这些值可能为零,也可能不是零.
np.empty
creates an array from available memory space, leaving whatever values happened to be hanging around in memory as the values. These values may or may not be zeros.
np.zeros
从可用内存空间创建一个数组,然后为您选择的dtype用零填充.显然np.zeros
必须做更多的工作,因此它应该更慢,因为它还会写入分配的内存.
np.zeros
creates an array from available memory space, and then fills it with zeros for your chosen dtype. Obviously np.zeros
has to do more work so it should be slower, since it's also writing to the memory allocated.
在np.empty
和np.ndarray
之间进行更公平的比较.
A more fair comparison would be between np.empty
and np.ndarray
.
这篇关于np.empty与np.zeros的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!