为什么第一次调用后Python中的矩阵向​​量乘法会更快?

时间:2018-09-22 20:57:14

标签: python numpy matrix-multiplication

我有以下代码:

import numpy as np
from timeit import default_timer as timer

n = 10
trials = 10

def test(scale=0.1):
    A = np.random.normal(scale=scale, size=(n, n))
    v = np.random.normal(scale=scale, size=(n))
    start = timer()
    A @ v
    end = timer()
    print('Time: ', end-start)

for _ in range(trials):
    test()

输出为:

Time:  0.0036287959665060043
Time:  7.0838723331689835e-06
Time:  3.401888534426689e-06
Time:  3.093155100941658e-06
Time:  3.0230730772018433e-06
Time:  3.037974238395691e-06

为什么前两个试验要慢得多?上下文是我正在一个项目中,在该项目中,我需要报告一种方法(在特殊情况下用于矩阵向量乘法)相对于一般矩阵向量乘法的加速。我是否应该忽略前几个试验?如果是,为什么?

0 个答案:

没有答案