Я немного изменился в цикле Rcpp, это проще, но он не может сильно ускориться:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector DSS_Rcpp(NumericMatrix d) {
int nc=d.ncol();
NumericVector a (nc);
for(int i=0; i<nc; ++i){
a(i)=sum(abs(rep(d( _ , i ),nc)-d));
}
return a;
}
/*** R
set.seed(0)
d <- matrix(rnorm(10000), nrow = 2)
DSS <- function(d) {
s <- ncol(d)
a <- vector("numeric", s)
for (i in 1:s)
{
L1 <- abs(d[, i ] - d)
a[i] <- sum(L1)
}
return(a)
}
library(microbenchmark)
microbenchmark(
a1 <- DSS(d),
a2 <- DSS_Rcpp(d),
times = 10L
)
*/
Единица: миллисекунды
expr min lq mean median uq max neval cld
a1 <- DSS(d) 125.4228 127.8480 134.4085 131.7876 134.3736 157.8660 10 a
a2 <- DSS_Rcpp(d) 404.6676 407.1085 414.5449 409.6840 421.5335 433.7639 10 b