File: newFib.r

package info (click to toggle)
rcpp 1.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,480 kB
  • sloc: cpp: 27,436; ansic: 7,778; sh: 53; makefile: 2
file content (32 lines) | stat: -rw-r--r-- 836 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/env 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