新的find_finite
和find_nonfinite
功能在犰狳4.300是很好的補充!在我使用Rcpp
的測試中,它們比標準循環慢大約2.5倍。以下是一些代碼,用於計算與R的na.rm=TRUE
選項對應的案例刪除的總和和平均值。來自R的性能基準測試表明,第一個版本(sum_arma
和mean_arma
)比迴路快大約3.5倍。我做的一切正確嗎?任何方式來提高性能?Armadillo的新find_finite函數比循環慢3.5倍?
C++代碼
#include <numeric>
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
double sum_arma1(arma::mat& X) {
double sum = 0;
for (int i = 0; i < X.size(); ++i) {
if (arma::is_finite(X(i)))
sum += X(i);
}
return sum;
}
// [[Rcpp::export]]
double sum_arma2(arma::mat& X) {
return arma::sum(X.elem(arma::find_finite(X)));
}
// [[Rcpp::export]]
double mean_arma1(arma::mat& X) {
double sum = 0;
int n = 0;
for (int i = 0; i < X.size(); ++i) {
if (arma::is_finite(X(i))) {
sum += X(i);
n += 1;
}
}
return sum/n;
}
// [[Rcpp::export]]
double mean_arma2(arma::mat& X) {
return arma::mean(X.elem(arma::find_finite(X)));
}
來自R基準測試結果
# data
X = matrix(rnorm(1e6),1000,1000)
X[sample(1:1000,100),sample(1:1000,100)] = NA
# equal?
all.equal(sum(X, na.rm=TRUE),sum_arma1(X))
all.equal(sum(X, na.rm=TRUE),sum_arma2(X))
all.equal(mean(X, na.rm=TRUE),mean_arma1(X))
all.equal(mean(X, na.rm=TRUE),mean_arma2(X))
# benchmark
benchmark(
sum(X, na.rm=TRUE),
sum_arma1(X),
sum_arma2(X),
replications=100)
# test replications elapsed relative user.self sys.self
# 2 sum_arma1(X) 100 0.259 1.000 0.259 0.001
# 3 sum_arma2(X) 100 1.035 3.996 0.750 0.293
# 1 sum(X, na.rm = TRUE) 100 0.491 1.896 0.492 0.003
benchmark(
mean(X, na.rm=TRUE),
mean_arma1(X),
mean_arma2(X),
replications=100)
# test replications elapsed relative user.self sys.self
# 2 mean_arma1(X) 100 0.252 1.00 0.253 0.001
# 3 mean_arma2(X) 100 0.819 3.25 0.620 0.206
# 1 mean(X, na.rm = TRUE) 100 7.440 29.52 7.120 0.373