[Rcpp-commits] r3010 - pkg/RcppArmadillo/inst/examples
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Sat Apr 23 18:18:10 CEST 2011
Author: edd
Date: 2011-04-23 18:18:09 +0200 (Sat, 23 Apr 2011)
New Revision: 3010
Modified:
pkg/RcppArmadillo/inst/examples/varSimulation.r
Log:
reordered slightly
Modified: pkg/RcppArmadillo/inst/examples/varSimulation.r
===================================================================
--- pkg/RcppArmadillo/inst/examples/varSimulation.r 2011-04-23 15:37:46 UTC (rev 3009)
+++ pkg/RcppArmadillo/inst/examples/varSimulation.r 2011-04-23 16:18:09 UTC (rev 3010)
@@ -19,8 +19,35 @@
## You should have received a copy of the GNU General Public License
## along with RcppArmadillo. If not, see <http://www.gnu.org/licenses/>.
+
+## parameter and error terms used throughout
+a <- matrix(c(0.5,0.1,0.1,0.5),nrow=2)
+e <- matrix(rnorm(10000),ncol=2)
+
+
+## Let's start with the R version
+rSim <- function(coeff, errors) {
+ simdata <- matrix(0, nrow(errors), ncol(errors))
+ for (row in 2:nrow(errors)) {
+ simdata[row,] = coeff %*% simdata[(row-1),] + errors[row,]
+ }
+ return(simdata)
+}
+
+rData <- rSim(a, e) # generated by R
+
+
+## Now let's load the R compiler (requires R 2.13 or later)
+suppressMessages(require(compiler))
+compRsim <- cmpfun(rSim)
+
+compRData <- compRsim(a,e) # generated by R 'compiled'
+
+stopifnot(all.equal(rData, compRData)) # checking results
+
+
+## Now load 'inline' to compile C++ code on the fly
suppressMessages(require(inline))
-
code <- '
arma::mat coeff = Rcpp::as<arma::mat>(a);
arma::mat errors = Rcpp::as<arma::mat>(e);
@@ -33,29 +60,15 @@
return Rcpp::wrap(simdata);
'
+## create the compiled function
rcppSim <- cxxfunction(signature(a="numeric",e="numeric"),
code,plugin="RcppArmadillo")
-a <- matrix(c(0.5,0.1,0.1,0.5),nrow=2)
-e <- matrix(rnorm(10000),ncol=2)
-rcppData <- rcppSim(a,e)
+rcppData <- rcppSim(a,e) # generated by C++ code
-rSim <- function(coeff,errors) {
- simdata <- matrix(0,nrow(errors),ncol(errors))
- for (row in 2:nrow(errors)) {
- simdata[row,] = coeff %*% simdata[(row-1),] + errors[row,]
- }
- return(simdata)
-}
-rData <- rSim(a,e)
-stopifnot(all.equal(rcppData, rData))
+stopifnot(all.equal(rData, rcppData)) # checking results
-suppressMessages(require(compiler))
-compRsim <- cmpfun(rSim)
-
-compRData <- compRsim(a,e)
-stopifnot(all.equal(rcppData, compRData))
-
+## now load the rbenchmark package and compare all three
library(rbenchmark)
res <- benchmark(rcppSim(a,e),
rSim(a,e),
More information about the Rcpp-commits
mailing list