[Rcpp-commits] r3930 - pkg/Rcpp/inst/examples/Misc
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Sat Nov 10 21:00:39 CET 2012
Author: edd
Date: 2012-11-10 21:00:39 +0100 (Sat, 10 Nov 2012)
New Revision: 3930
Added:
pkg/Rcpp/inst/examples/Misc/newFib.r
Log:
simple attributes version of the fibonacci comparison
Added: pkg/Rcpp/inst/examples/Misc/newFib.r
===================================================================
--- pkg/Rcpp/inst/examples/Misc/newFib.r (rev 0)
+++ pkg/Rcpp/inst/examples/Misc/newFib.r 2012-11-10 20:00:39 UTC (rev 3930)
@@ -0,0 +1,32 @@
+#!/usr/bin/r
+
+## New and shorter version of Fibonacci example using Rcpp 0.9.16 or later features
+## The the sibbling file 'fibonacci.r' for context
+
+require(Rcpp) # no longer need inline
+
+## R version
+fibR <- function(seq) {
+ if (seq < 2) return(seq)
+ return (fibR(seq - 1) + fibR(seq - 2))
+}
+
+## C++ code
+cpptxt <- '
+int fibonacci(const int x) {
+ if (x < 2) return(x);
+ return (fibonacci(x - 1)) + fibonacci(x - 2);
+}'
+
+## C++ version
+fibCpp <- cppFunction(cpptxt) # compiles, load, links, ...
+
+## load rbenchmark to compare
+library(rbenchmark)
+
+N <- 35 ## same parameter as original post
+res <- benchmark(fibR(N), fibCpp(N),
+ columns=c("test", "replications", "elapsed", "relative"),
+ order="relative", replications=1)
+print(res) ## show result
+
More information about the Rcpp-commits
mailing list