Rcpp Version 1.0.14
Loading...
Searching...
No Matches
newFib.r
Go to the documentation of this file.
1#!/usr/bin/env r
2
3## New and shorter version of Fibonacci example using Rcpp 0.9.16 or later features
4## The the sibbling file 'fibonacci.r' for context
5
6require(Rcpp) # no longer need inline
7
8## R version
9fibR <- function(seq) {
10 if (seq < 2) return(seq)
11 return (fibR(seq - 1) + fibR(seq - 2))
12}
13
14## C++ code
15cpptxt <- '
16int fibonacci(const int x) {
17 if (x < 2) return(x);
18 return (fibonacci(x - 1)) + fibonacci(x - 2);
19}'
20
21## C++ version
22fibCpp <- cppFunction(cpptxt) # compiles, load, links, ...
23
24## load rbenchmark to compare
25library(rbenchmark)
26
27N <- 35 ## same parameter as original post
28res <- benchmark(fibR(N), fibCpp(N),
29 columns=c("test", "replications", "elapsed", "relative"),
30 order="relative", replications=1)
31print(res) ## show result
32