python矩阵运算库效率_python – MATLAB矩阵乘法性能比NumPy快5倍

我在MATLAB& amp;中设置了两个相同的测试.关于矩阵乘法与广播的

Python.对于

Python,我使用了NumPy,对于MATLAB,我使用了使用BLAS的

mtimesx库.

MATLAB

close all; clear;

N = 1000 + 100; % a few initial runs to be trimmed off at the end

a = 100;

b = 30;

c = 40;

d = 50;

A = rand(b, c, a);

B = rand(c, d, a);

C = zeros(b, d, a);

times = zeros(1, N);

for ii = 1:N

tic

C = mtimesx(A,B);

times(ii) = toc;

end

times = times(101:end) * 1e3;

plot(times);

grid on;

title(median(times));

Python

import timeit

import numpy as np

import matplotlib.pyplot as plt

N = 1000 + 100 # a few initial runs to be trimmed off at the end

a = 100

b = 30

c = 40

d = 50

A = np.arange(a * b * c).reshape([a, b, c])

B = np.arange(a * c * d).reshape([a, c, d])

C = np.empty(a * b * d).reshape([a, b, d])

times = np.empty(N)

for i in range(N):

start = timeit.default_timer()

C = A @ B

times[i] = timeit.default_timer() - start

times = times[101:] * 1e3

plt.plot(times, linewidth=0.5)

plt.grid()

plt.title(np.median(times))

plt.show()

>我的Python是使用OpenBLAS从pip安装的默认Python.

>我正在使用英特尔NUC i3.

MATLAB代码在1ms运行,而Python在5.8ms运行,我无法弄清楚为什么,因为它们似乎都在使用BLAS.

编辑

来自Anaconda:

In [7]: np.__config__.show()

mkl_info:

libraries = ['mkl_rt']

library_dirs = [...]

define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]

include_dirs = [...]

blas_mkl_info:

libraries = ['mkl_rt']

library_dirs = [...]

define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]

include_dirs = [...]

blas_opt_info:

libraries = ['mkl_rt']

library_dirs = [...]

define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]

include_dirs = [...]

lapack_mkl_info:

libraries = ['mkl_rt']

library_dirs = [...]

define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]

include_dirs = [...]

lapack_opt_info:

libraries = ['mkl_rt']

library_dirs = [...]

define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]

include_dirs = [...]

从numpy使用pip

In [2]: np.__config__.show()

blas_mkl_info:

NOT AVAILABLE

blis_info:

NOT AVAILABLE

openblas_info:

library_dirs = [...]

libraries = ['openblas']

language = f77

define_macros = [('HAVE_CBLAS', None)]

blas_opt_info:

library_dirs = [...]

libraries = ['openblas']

language = f77

define_macros = [('HAVE_CBLAS', None)]

lapack_mkl_info:

NOT AVAILABLE

openblas_lapack_info:

library_dirs = [...]

libraries = ['openblas']

language = f77

define_macros = [('HAVE_CBLAS', None)]

lapack_opt_info:

library_dirs = [...]

libraries = ['openblas']

language = f77

define_macros = [('HAVE_CBLAS', None)]

编辑2

我试图用np.matmul(A,B,out = C)代替C = A @ B,并且时间缩短2倍,例如大约11ms.这真的很奇怪.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值