我在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.这真的很奇怪.