2suppressMessages(library(Rcpp))
3suppressMessages(library(inline))
4suppressMessages(library(rbenchmark))
6## NOTE: Within this section, the new way to compile Rcpp code inline has been
7## written. Please use the code next as a template for your own project, and
8## do NOT use the old code below
11NumericVector rcppGamma(NumericVector x){
14 const double y = 1.234;
15 for (int i=0; i<n; i++) {
16 x[i] = R::rgamma(3.0, 1.0/(y*y+4));
23## This approach is a bit sloppy. Generally, you will want to use
24## sourceCpp() if there are additional includes that are required.
26NumericVector gslGamma(NumericVector x){
29 gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);
30 const double y = 1.234;
31 for (int i=0; i<n; i++) {
32 x[i] = gsl_ran_gamma(r,3.0,1.0/(y*y+4));
38}', includes = '#include <gsl/gsl_rng.h>
39 #include <gsl/gsl_randist.h>',
44NumericVector rcppNormal(NumericVector x){
47 const double y = 1.234;
48 for (int i=0; i<n; i++) {
49 x[i] = R::rnorm(1.0/(y+1),1.0/sqrt(2*y+2));
57## Here we demonstrate the use of sourceCpp() to show the continuity
58## of the code artifact.
62#include <gsl/gsl_rng.h>
63#include <gsl/gsl_randist.h>
67// [[Rcpp::depends("RcppGSL")]]
70NumericVector gslNormal(NumericVector x){
73 gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);
74 const double y = 1.234;
75 for (int i=0; i<n; i++) {
76 x[i] = 1.0/(y+1)+gsl_ran_gaussian(r,1.0/sqrt(2*y+2));
85res <- benchmark(rcppGamma(x),
89 columns=c("test", "replications", "elapsed", "relative", "user.self", "sys.self"),
100## Old code below. Do not use in new projects, it is here solely for comparison
105## NOTE: This is the old way to compile Rcpp code inline.
106## The code here has left as a historical artifact and tribute to the old way.
107## Please use the code under the "new" inline compilation section.
109rcppGamma_old <- cxxfunction(signature(xs="numeric"), plugin="Rcpp", body='
113 RNGScope scope; // Initialize Random number generator. Not needed when Attributes used.
115 const double y = 1.234;
116 for (int i=0; i<n; i++) {
117 x[i] = ::Rf_rgamma(3.0, 1.0/(y*y+4));
125gslGamma_old <- cxxfunction(signature(xs="numeric"), plugin="RcppGSL",
126 include='#include <gsl/gsl_rng.h>
127 #include <gsl/gsl_randist.h>',
132 gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);
133 const double y = 1.234;
134 for (int i=0; i<n; i++) {
135 x[i] = gsl_ran_gamma(r,3.0,1.0/(y*y+4));
144rcppNormal_old <- cxxfunction(signature(xs="numeric"), plugin="Rcpp", body='
148 RNGScope scope; // Initialize Random number generator. Not needed when Attributes used.
150 const double y = 1.234;
151 for (int i=0; i<n; i++) {
152 x[i] = ::Rf_rnorm(1.0/(y+1),1.0/sqrt(2*y+2));
160gslNormal_old <- cxxfunction(signature(xs="numeric"), plugin="RcppGSL",
161 include='#include <gsl/gsl_rng.h>
162 #include <gsl/gsl_randist.h>',
167 gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);
168 const double y = 1.234;
169 for (int i=0; i<n; i++) {
170 x[i] = 1.0/(y+1)+gsl_ran_gaussian(r,1.0/sqrt(2*y+2));