Last active
December 16, 2015 04:39
-
-
Save pbalduino/5379156 to your computer and use it in GitHub Desktop.
Example of memoization use in Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; First we create a function. Let's try Fibonacci | |
(defn fib [n] | |
(if (or (zero? n) (= n 1)) | |
1 | |
(+ (fib (dec n) ) (fib (- n 2))))) | |
; Se let's measure the time needed to run the function | |
(do | |
(time (fib 30)) | |
(time (fib 30)) | |
(time (fib 30))) | |
; "Elapsed time: 398.613 msecs" | |
; "Elapsed time: 397.204 msecs" | |
; "Elapsed time: 398.835 msecs" | |
; 1346269 | |
; Now let's memoize fib and store the result in fib-memo. Let's measure the time again | |
(let [fib-memo (memoize fib)] | |
(time (fib-memo 30)) | |
(time (fib-memo 30)) | |
(time (fib-memo 30))) | |
; "Elapsed time: 398.870 msecs" | |
; "Elapsed time: 0.007 msecs" | |
; "Elapsed time: 0.005 msecs" | |
; 1346269 | |
; 57000x ~ 79000x faster is good enough for you? | |
; Anyway don't expect miracles: | |
(let [fib-memo (memoize fib)] | |
(time (fib-memo 30)) | |
(time (fib-memo 31)) | |
(time (fib-memo 32))) | |
; "Elapsed time: 399.709 msecs" | |
; "Elapsed time: 647.915 msecs" | |
; "Elapsed time: 1052.429 msecs" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment