首页 > 解决方案 > 为什么 Numpy 操作 0.1M 矩阵 1000 次比操作 1M 矩阵 100 次要快得多?

问题描述

我发现了一个奇怪的现象,即 Numpy 在操作较小的矩阵时似乎要快得多,即使在数据总量相同的情况下也是如此。为什么会这样?

import time

import numpy as np


def a():
    ts = time.time()
    for i in range(100):
        x = np.random.rand(100000, 2).reshape(-1, 2)
        y = np.random.rand(100000)
    te = time.time()
    print(te - ts)


def b():
    ts = time.time()
    for i in range(1000):
        x = np.random.rand(10000, 2).reshape(-1, 2)
        y = np.random.rand(10000)
    te = time.time()
    print(te - ts)


a()
b()
a()
0.30100059509277344
0.25199460983276367
0.30100131034851074

标签: pythonnumpy

解决方案


如果您不使用该time库,它们大致相同 - 这是有道理的。计算函数时间的变化是巨大的。只有一次不会验证一个函数是否更快(如果它没有明显更快)。

def a():
    for i in range(100):
        x = np.random.rand(100000, 2).reshape(-1, 2)
        y = np.random.rand(100000)


def b():
    for i in range(1000):
        x = np.random.rand(10000, 2).reshape(-1, 2)
        y = np.random.rand(10000)

%%timeit -n100 -r10
a()
225 ms ± 4.78 ms per loop (mean ± std. dev. of 10 runs, 100 loops each)

%%timeit -n100 -r10
b()
224 ms ± 2.86 ms per loop (mean ± std. dev. of 10 runs, 100 loops each)


推荐阅读