我发现len(arr)几乎是arr.shape [0]的两倍,我想知道为什么.
我使用的是Python 3.5.2,Numpy 1.14.2,IPython 6.3.1
以下代码演示了这一点:
arr = np.random.randint(1, 11, size=(3, 4, 5))
%timeit len(arr)
# 62.6 ns ± 0.239 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit arr.shape[0]
# 102 ns ± 0.163 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
我还做了一些比较测试:
class Foo():
def __init__(self):
self.shape = (3, 4, 5)
foo = Foo()
%timeit arr.shape
# 75.6 ns ± 0.107 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit foo.shape
# 61.2 ns ± 0.281 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit foo.shape[0]
# 78.6 ns ± 1.03 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
所以我有两个问题:
1)为什么len(arr)的工作速度比arr.shape [0]快? (我原以为len会因为函数调用而变慢)
2)为什么foo.shape [0]的工作速度比arr.shape [0]快? (换句话说,在这种情况下,numpy数组会产生什么开销呢?)