繁体   English   中英

为什么使用矩阵乘法时Rcpp比R慢?

[英]why Rcpp is slower than R when using matrix multiply?

为了加快我的程序包(其中包括大量矩阵计算)的速度,我使用Rcpp重写所有代码。 但是,某些功能甚至比以前慢。 我使用微基准进行分析,发现Rcpp中的矩阵乘法比较慢。 为什么会这样? 以及如何加速我的包裹? 非常感谢。 Rcpp代码如下:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericMatrix mmult(const NumericMatrix& a, const NumericMatrix& b){
if (a.ncol() != b.nrow()) stop ("Incompatible matrix dimensions");
NumericMatrix out(a.nrow(),b.ncol());
NumericVector rm1, cm2;
for (int i = 0; i < a.nrow(); ++i) {
  rm1 = a(i,_);
  for (int j = 0; j < b.ncol(); ++j) {
    cm2 = b(_,j);
    out(i,j) = std::inner_product(rm1.begin(), rm1.end(), cm2.begin(), 0.);
  }
}
return out;}

R代码如下:

X = matrix(rnorm(10*10,1),10,10)
Y = matrix(rnorm(10*10,1),10,10)


microbenchmark(
  mmult(X,Y),
  X%*%Y)

结果是:

Unit: microseconds
    expr    min      lq      mean median     uq      max neval
 mmult(X, Y) 45.720 48.9860 126.79228 50.385 51.785 6368.512   100
 X %*% Y  5.599  8.8645  12.85787  9.798 10.730  153.486   100

这与矩阵向量乘法所看到的结果相反,但却是预期的结果。 在这里R正在使用BLAS进行所有繁重的工作,甚至可能并行工作。 通过使用朴素矩阵乘法,您将放弃在BLAS库中完成的所有优化的内存管理。

您可以尝试使用RcppArmadillo之类的东西来实现代码的较大部分,而不是尝试重塑矩阵乘法之类的低级内容,它使用与R相同的BLAS库,而且(不仅!)在顶部提供了一种方便的语法。其中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM