Rcpp - 加速 for 和 while 循环内的随机正常绘制

Jin*_*tar 4 random r while-loop rcpp

我是 Rcpp 的新手,正在探索它的应用程序。特别是,我正在尝试加速以下功能,部分基于之前的答案

code = 'NumericVector RcppFun(int N){
            NumericVector out(N);
            for (int i = 0; i < N; ++i) {
                double V = 0;
                while( V > -1e04 && V < 1e04 ) {
                    V += R::rnorm(10, 100);
                    }
                out[i] = V;
                }
            return out;
            }'
cppFunction(code)
system.time(RcppFun(1e05))
Run Code Online (Sandbox Code Playgroud)

该代码比 R 对应的代码快得多,但在我的计算机上运行仍需要几秒钟。鉴于我需要多次调用这个函数,我想知道是否可以进一步提高它的性能。

我在想修改 while 循环内的逻辑语句或更改 RNG 函数会以某种方式使函数更快,但我不知道如何实现。

谢谢您的任何建议!

编辑:为了完整性,这里是我根据 Dirk 非常有用的建议用 C++ 编写的代码:

#include <Rcpp.h>
// [[Rcpp::depends(RcppZiggurat)]]
#include <Ziggurat.h>
using namespace Rcpp;
static Ziggurat::Ziggurat::Ziggurat zigg;
// [[Rcpp::export]]
NumericVector ZiggFun(int N){
            NumericVector out(N);
            for (int i = 0; i < N; ++i) {
                double V = 0;
                while( V > -1e04 && V < 1e04 ) {
                    V += 10 + zigg.norm()*100;
                    }
                out[i] = V;
                }
            return out;
            }
Run Code Online (Sandbox Code Playgroud)

根据 rbenchmark::benchmark 估计,新代码现在速度快了 7 倍以上!

Dir*_*tel 5

您可以使用 RcppZiggurat 进行更快的 RNG 抽签——我在包中进行了时间比较:

R> library(RcppZiggurat)
R> library(microbenchmark)
R> microbenchmark(rnorm(1e5), zrnorm(1e5))
Unit: microseconds
          expr      min       lq    mean   median       uq      max neval cld
  rnorm(1e+05) 6148.781 6169.917 6537.31 6190.073 6923.357 10166.96   100   b
 zrnorm(1e+05)  719.458  887.554 1016.03  901.182  939.652  2880.47   100  a 
R> 
Run Code Online (Sandbox Code Playgroud)

该 RNG 也可以在 C++ 级别的其他包中使用。它只是您以通常方式拉取的标头。