gpt4 book ai didi

python - Numpy 中 zeros 函数的性能

转载 作者:可可西里 更新时间:2023-11-01 13:48:32 24 4
gpt4 key购买 nike

我刚刚注意到 numpyzeros 函数有一个奇怪的行为:

%timeit np.zeros((1000, 1000))
1.06 ms ± 29.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit np.zeros((5000, 5000))
4 µs ± 66 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

另一方面,ones 似乎有一个正常的行为。有人知道为什么用 zeros 函数初始化一个小的 numpy 数组比用一个大数组初始化一个小数组要花更多的时间吗?

(Python 3.5,numpy 1.11)

最佳答案

这看起来像 calloc 达到了一个阈值,它向操作系统请求归零内存并且不需要手动初始化它。翻遍源码,numpy.zeros最终delegates to calloc获取一个归零的内存块,如果你比较 numpy.empty,它不执行初始化:

In [15]: %timeit np.zeros((5000, 5000))
The slowest run took 12.65 times longer than the fastest. This could mean that a
n intermediate result is being cached.
100000 loops, best of 3: 10 µs per loop

In [16]: %timeit np.empty((5000, 5000))
The slowest run took 5.05 times longer than the fastest. This could mean that an
intermediate result is being cached.
100000 loops, best of 3: 10.3 µs per loop

可以看到 np.zeros 对于 5000x5000 数组没有初始化开销。

事实上,在您尝试访问它之前,操作系统甚至不会“真正地”分配该内存。对 TB 级数组的请求在没有 TB 级空闲空间的机器上成功:

In [23]: x = np.zeros(2**40)  # No MemoryError!

关于python - Numpy 中 zeros 函数的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47932922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com