Chapter 2 Fibonacci Sequences One

R

fib1_r <- function(n) {
    if (n == 0) return(0)
    if (n == 1) return(1)
    return (fib1_r(n - 1) + fib1_r(n - 2))
}

C++

int fib1_cpp(const int x) {
    if (x == 0) return(0);
    if (x == 1) return(1);
    return (fibonacci(x - 1)) + fibonacci(x - 2);
}

Rust

pub fn fib1_rs(x:u64)-> u64{
    if x == 0 { return(0) };
    if x == 1 { return(1) };
    return (fib1_rs(x - 1)) + fib1_rs(x - 2);
}

R script

library(Rcpp)
library(rustinr)
library(microbenchmark)

fib1_r <- function(n) {
    if (n == 0) return(0)
    if (n == 1) return(1)
    return (fib1_r(n - 1) + fib1_r(n - 2))
}

sourceCpp(code = '
// [[Rcpp::export]]
int fib1_cpp(const int x) {
    if (x == 0) return(0);
    if (x == 1) return(1);
    return (fib1_cpp(x - 1)) + fib1_cpp(x - 2);
}')

rust(code = '
// #[rustr_export]
pub fn fib1_rs(x:u64)-> u64{
    if x == 0 { return(0) };
    if x == 1 { return(1) };
    return (fib1_rs(x - 1)) + fib1_rs(x - 2);
}')

microbenchmark(fib1_r(10L),fib1_cpp(10L),fib1_rs(10L))
#> Unit: microseconds
#>           expr    min     lq   mean median     uq   max neval
#>    fib1_r(10L) 182.11 203.76 235.49 225.72 254.77 507.8   100
#>  fib1_cpp(10L)   1.49   2.21   3.54   2.61   3.49  23.2   100
#>   fib1_rs(10L)   1.32   1.78   3.12   2.42   3.10  31.8   100