効率を本当に気にするなら、この短いRcppコードを打ち負かすのは難しいでしょう。以下をファイルに保存します/tmp/rnormClamp.cpp
。
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector rnormClamp(int N, int mi, int ma) {
NumericVector X = rnorm(N, 0, 1);
return clamp(mi, X, ma);
}
/*** R
system.time(X <- rnormClamp(50000, -3, 3))
summary(X)
*/
sourceCpp()
(Rcppからも)を使用してビルドおよび実行します。私のコンピューターでは、実際の描画とクランプには約4ミリ秒かかります。
R> sourceCpp("/tmp/rnormClamp.cpp")
R> system.time(X <- rnormClamp(50000, -3, 3))
user system elapsed
0.004 0.000 0.004
R> summary(X)
Min. 1st Qu. Median Mean 3rd Qu. Max.
-3.00000 -0.67300 -0.00528 0.00122 0.68500 3.00000
R>
clamp()
砂糖関数は、Romainによるこの以前のSO回答で取り上げられました。これは、Rcppのバージョン0.10.2が必要であることも示しています。
Edit: Per Ben's hint, I seemed to have misunderstood. Here is a mix of C++ and R:
// [[Rcpp::export]]
List rnormSelect(int N, int mi, int ma) {
RNGScope scope;
int N2 = N * 1.25;
NumericVector X = rnorm(N2, 0, 1);
LogicalVector ind = (X < mi) | (X > ma);
return List::create(X, ind);
}
which one can append to the earlier file. Then:
R> system.time({ Z <- rnormSelect(50000, -3, 3);
+ X <- Z[[1]][ ! Z[[2]] ]; X <- X[1:50000]})
user system elapsed
0.008 0.000 0.009
R> summary(X)
Min. 1st Qu. Median Mean 3rd Qu. Max.
-3.00000 -0.68200 -0.00066 -0.00276 0.66800 3.00000
R>
I'll revisit to the logical indexing and the row subset which I'll have to look up. Maybe tomorrow. But 9 milliseconds is still not too bad :)
Edit 2: Looks like we really don't have logical indexing. We'll have to add this. This version does it 'by hand' but is not that much faster than indexing from R:
// [[Rcpp::export]]
NumericVector rnormSelect2(int N, int mi, int ma) {
RNGScope scope;
int N2 = N * 1.25;
NumericVector X = rnorm(N2, 0, 1);
LogicalVector ind = (X >= mi) & (X <= ma);
NumericVector Y(N);
int k=0;
for (int i=0; i<N2 & k<N; i++) {
if (ind[i]) Y(k++) = X(i);
}
return Y;
}
And the output:
R> system.time(X <- rnormSelect2(50000, -3, 3))
user system elapsed
0.004 0.000 0.007
R> summary(X)
Min. 1st Qu. Median Mean 3rd Qu. Max.
-2.99000 -0.66900 -0.00258 0.00223 0.66700 2.99000
R> length(X)
[1] 50000
R>