Skip to content

Instantly share code, notes, and snippets.

@tobigithub
Last active September 27, 2015 03:30
Show Gist options
  • Save tobigithub/aa741742a1fff7690dd5 to your computer and use it in GitHub Desktop.
Save tobigithub/aa741742a1fff7690dd5 to your computer and use it in GitHub Desktop.
# library(memoise) can speed up code 1000x fold
# for true speed-up on fibonacci use library(gmp) fibnum(n)
# http://adv-r.had.co.nz/Function-operators.html
# https://cran.r-project.org/web/packages/memoise/memoise.pdf
# Tobias Kind (2015) https://gist.github.com/tobigithub
library(memoise)
# no memoise()
fib1 <- function(n) {
if (n < 2) return(1)
fib1(n - 2) + fib1(n - 1)
}
# Use of memoise() library
fib2 <- memoise(function(n) {
if (n < 2) return(1)
fib2(n - 2) + fib2(n - 1)
})
# set number of Fibonaccis;
fibs = 30
# to see calculation Push Ctrl-W (turn buffer off)
cat("Warning no memoise() very slow!\n");
for (i in 1:fibs) {cat(i, fib1(i),"\n");};
cat("Warning with memoise() very fast!\n");
for (i in 1:fibs) {cat(i, fib2(i),"\n");};
# benchmark again
t1 <-system.time({fib1_result = fib1(fibs)})
t2 <-system.time({fib2_result = fib2(fibs)})
# gimme text
cat(" No memoise() result : ",fib1_result," in " ,as.numeric(t1[3])," seconds\n")
cat(" With memoise() result: ",fib2_result," in " ,as.numeric(t2[3])," seconds \n")
cat(" Using library(memoise) will be ", as.numeric(t1[3])/as.numeric(t2[3]), " times faster!\n")
# plot results in bargraph
x = c("No library (memoise)", "library (memoise)")
y = c(as.numeric(t1[3]), as.numeric(t2[3]))
speedup = as.numeric(t1[3])/as.numeric(t2[3])
legend = paste("Using R library(memoise) is " ,round(speedup,0) , "fold faster")
barplot(y, main=legend,names = x, xlab="Time [s]", col=c("red","green"),horiz=TRUE)
#?memoise
# Results for fibs = 33 (3.1 Ghz Xeon)
# No memoise() result : 5702887 in 9.45 seconds
# With memoise() result: 5702887 in 0.01 seconds
# Using library(memoise) will be 1507 times faster!
# fib2(1475)
# [1] 1.306989e+308
# microbenchmark(fib2(1475))
# 42 microseconds on 4 Ghz Core-i7 CPU
#
# cleanup if needed
# rm(list=ls(all=TRUE))
### END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment