簡體   English   中英

為什么我的例子中的Rcpp實現比R函數慢得多?

[英]Why is the Rcpp implementation in my example much slower than the R function?

我有一些C ++和R的經驗,但我是Rcpp的新手。 最近我在之前的一些項目中使用Rcpp取得了巨大成功,因此決定將其應用於新項目。 我很驚訝我的Rcpp代碼可能比相應的R函數慢得多。 我試圖簡化我的R函數來找出原因,但找不到任何線索。 非常歡迎您的幫助和意見!

比較R和Rcpp實現的主要R函數:

main <- function(){

  n <- 50000
  Delta <- exp(rnorm(n))
  delta <- exp(matrix(rnorm(n * 5), nrow = n))
  rx <- matrix(rnorm(n * 20), nrow = n)
  print(microbenchmark(c1 <- test(Delta, delta, rx), times = 500))
  print(microbenchmark(c2 <- rcpp_test(Delta, delta, rx), times = 500))

  identical(c1, c2)
  list(c1 = c1, c2 = c2)
}

R實施:

test <- function(Delta, delta, rx){

  const <- list()
  for(i in 1:ncol(delta)){
    const[[i]] <- rx * (Delta / (1 + delta[, i]))
  }

  const

}

Rcpp實現:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List rcpp_test(NumericVector Delta, 
               NumericMatrix delta, 
               NumericMatrix rx) {

  int n = Delta.length();
  int m = rx.ncol();

  List c; 
  NumericMatrix c1;
  for(int i = 0; i < delta.ncol(); ++i){
    c1 = NumericMatrix(n, m);
    for(int k = 0; k < n; ++k){
      double tmp = Delta[k] / (1 + delta(k, i));
      for(int j = 0; j < c1.ncol(); ++j){
        c1(k, j) = rx(k, j) * tmp; 
      }
    }
    c.push_back(c1);
  }

  return c;

}

我知道使用Rcpp並不能保證提高效率,但鑒於我在這里展示的簡單示例,我不明白為什么Rcpp代碼運行得如此之慢。

Unit: milliseconds
                         expr      min       lq     mean   median       uq      max neval
 c1 <- test(Delta, delta, rx) 13.16935 14.19951 44.08641 30.43126 73.78581 115.9645   500
Unit: milliseconds
                              expr      min       lq     mean  median       uq      max neval
 c2 <- rcpp_test(Delta, delta, rx) 143.1917 158.7481 171.6116 163.413 173.7677 247.5495   500

理想情況下, rx是我項目中的矩陣列表。 for循環中的變量i將用於選擇要計算的元素。 一開始我懷疑將List傳遞給Rcpp可能會有很高的開銷,所以在這個例子中,我假設rx是一個用於所有i的固定矩陣。 似乎這不是緩慢的原因。

您的R代碼似乎或多或少是最優的,即所有實際工作都是在編譯代碼中完成的。 對於C ++代碼,我可以找到的主要問題是在緊密循環中調用c1.ncol() 如果我用m替換它,C ++解決方案幾乎和R一樣快。如果我添加RcppArmadillo混合,我得到一個非常緊湊的語法,但不比純Rcpp代碼快。 對我而言,這表明編寫好的R代碼真的很難:

//  [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
List arma_test(const arma::vec& Delta,
           const arma::mat& delta,
           const arma::mat& rx) {
  int l = delta.n_cols;
  List c(l);

  for (int i = 0; i < l; ++i) {
    c(i) = rx.each_col() % (Delta / (1 + delta.col(i)));
  }

  return c;  
}

// [[Rcpp::export]]
List rcpp_test(NumericVector Delta, 
               NumericMatrix delta, 
               NumericMatrix rx) {

  int n = Delta.length();
  int m = rx.ncol();

  List c(delta.ncol()); 
  NumericMatrix c1;
  for(int i = 0; i < delta.ncol(); ++i){
    c1 = NumericMatrix(n, m);
    for(int k = 0; k < n; ++k){
      double tmp = Delta[k] / (1 + delta(k, i));
      for(int j = 0; j < m; ++j){
        c1(k, j) = rx(k, j) * tmp; 
      }
    }
    c(i) = c1;
  }

  return c;

}

/*** R
test <- function(Delta, delta, rx){

  const <- list()
  for(i in 1:ncol(delta)){
    const[[i]] <- rx * (Delta / (1 + delta[, i]))
  }

  const

}

n <- 50000
Delta <- exp(rnorm(n))
delta <- exp(matrix(rnorm(n * 5), nrow = n))
rx <- matrix(rnorm(n * 20), nrow = n)
bench::mark(test(Delta, delta, rx),
            arma_test(Delta, delta, rx),
            rcpp_test(Delta, delta, rx))
 */

輸出:

# A tibble: 3 x 14
  expression     min    mean  median     max `itr/sec` mem_alloc  n_gc n_itr
  <chr>      <bch:t> <bch:t> <bch:t> <bch:t>     <dbl> <bch:byt> <dbl> <int>
1 test(Delt…  84.3ms  85.2ms  84.9ms  86.6ms     11.7     44.9MB     2     4
2 arma_test… 106.5ms 107.7ms 107.7ms 108.9ms      9.28    38.1MB     3     2
3 rcpp_test… 101.9ms 103.2ms 102.2ms 106.6ms      9.69    38.1MB     1     4
# … with 5 more variables: total_time <bch:tm>, result <list>, memory <list>,
#   time <list>, gc <list>

我還明確地將輸出列表初始化為所需的大小,避免了push_back ,但這並沒有產生很大的影響。 使用來自Rcpp的數據結構的向量,你應該絕對避免使用push_back ,因為每次擴展向量時都會產生一個副本。

我想補充一下@RalfStubner的優秀答案。

您會注意到我們在第一個for循環中進行了許多分配(即c1 = NumerMatrix(n, m) )。 這可能很昂貴,因為我們除了分配內存外,還將每個元素初始化為0。 為了提高效率,我們可以將其更改為以下內容:

NumericMatrix c1 = no_init_matrix(n, m)

我也繼續並盡可能地添加關鍵字const 如果這樣做允許編譯器優化某些代碼片段是值得商榷的,但我仍然將其添加到我能夠代碼清晰度的地方(即“我不希望這個變量改變” )。 有了這個,我們有:

// [[Rcpp::export]]
List rcpp_test_modified(const NumericVector Delta, 
                        const NumericMatrix delta, 
                        const NumericMatrix rx) {

    int n = Delta.length();
    int m = rx.ncol();
    int dCol = delta.ncol();

    List c(dCol);

    for(int i = 0; i < dCol; ++i) {
        NumericMatrix c1 = no_init_matrix(n, m);

        for(int k = 0; k < n; ++k) {
            const double tmp = Delta[k] / (1 + delta(k, i));

            for(int j = 0; j < m; ++j) {
                c1(k, j) = rx(k, j) * tmp; 
            }
        }

        c[i] = c1;
    }

    return c;

}

以下是一些基准測試( Armadillo解決方案遺漏):

bench::mark(test(Delta, delta, rx),
            rcpp_test_modified(Delta, delta, rx),
            rcpp_test(Delta, delta, rx))
# A tibble: 3 x 14
  expression     min   mean  median    max `itr/sec` mem_alloc  n_gc n_itr total_time result memory time 
  <chr>      <bch:t> <bch:> <bch:t> <bch:>     <dbl> <bch:byt> <dbl> <int>   <bch:tm> <list> <list> <lis>
1 test(Delt… 12.27ms 17.2ms 14.56ms 29.5ms      58.1    41.1MB    13     8      138ms <list… <Rpro… <bch…
2 rcpp_test…  7.55ms 11.4ms  8.46ms   26ms      87.8    38.1MB    16    21      239ms <list… <Rpro… <bch…
3 rcpp_test… 10.36ms 15.8ms 13.64ms 28.9ms      63.4    38.1MB    10    17      268ms <list… <Rpro… <bch…
# … with 1 more variable: gc <list>

我們看到Rcpp版本提高了50%

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM