When computing A @ a where A is a random N by N matrix and a is a vector with N random elements using numpy the computation time jumps by an order of magnitude at N=100. Is there any particular reason for this? As a comparison the same operation using torch on the cpu has a more gradual increasematrix-vector multiply computation time

用同样的行为try 了python3.10、3.9和3.7

用于生成图形的Numpy部分的代码:

import numpy as np
from tqdm.notebook import tqdm
import pandas as pd
import time
import sys

def sym(A):
    return .5 * (A + A.T)

results = []
for n in tqdm(range(2, 500)):
    for trial_idx in range(10):
        A = sym(np.random.randn(n, n))
        a = np.random.randn(n)        
        
        t = time.time()
        for i in range(1000):
            A @ a
        t = time.time() - t
        results.append({
            'n': n,
            'time': t,
            'method': 'numpy',
        })
results = pd.DataFrame(results)

from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.semilogy(results.n.unique(), results.groupby('n').time.mean(), label="numpy")
ax.set_title(f'A @ a timimgs (1000 times)\nPython {sys.version.split(" ")[0]}')
ax.legend()
ax.set_xlabel('n')
ax.set_ylabel('avg. time')

更新

添加

import os
os.environ["MKL_NUM_THREADS"] = "1" 
os.environ["NUMEXPR_NUM_THREADS"] = "1" 
os.environ["OMP_NUM_THREADS"] = "1" 

before ìmport numpy gives a more expected output, see this answer for details: https://stackoverflow.com/a/74662135/5043576 update

推荐答案

numpy在对大小为100或更大的矩阵进行乘法时try 使用线程,而线程乘法的默认CBLAS实现是…次优的,而不是像intel MKL或ATLAS这样的其他后端.

如果你强迫它只使用一个使用answers in this post的线程,你会得到一条连续的线条来获得麻木的性能.

Python相关问答推荐

如何根据参数推断对象的返回类型?

可变参数数量的重载类型(args或kwargs)

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

将pandas Dataframe转换为3D numpy矩阵

在matplotlib中删除子图之间的间隙_mosaic

幂集,其中每个元素可以是正或负""""

如何在海上配对图中使某些标记周围的黑色边框

巨 Python :逆向猜谜游戏

计算空值

当条件满足时停止ODE集成?

为什么Python内存中的列表大小与文档不匹配?

在Google Drive中获取特定文件夹内的FolderID和文件夹名称

Pandas 数据帧中的枚举,不能在枚举列上执行GROUP BY吗?

将字节序列解码为Unicode字符串

递归链表反转与打印语句挂起

将标签与山脊线图对齐

Django-修改后的管理表单返回对象而不是文本

意外的麻木图像reshape 为网格问题

如何在包含时间戳的词典列表中找到每天的第一个时间?

滑动子数组美容工作在IDE上,但不是在leetcode上