Created
May 8, 2018 03:35
-
-
Save twlz0ne/c17c936340b89bf1af282fed6303416c to your computer and use it in GitHub Desktop.
Test fibonacci #emacs-lisp
This file contains 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
;;; test-fibonacci.el --- Test fibonacci -*- lexical-binding: t; -*- | |
;;; Usage: /path/to/emacs --batch -l /path/to/test-fibonacci.el | |
;;; Date: 2018-05-08_11.32.38 | |
(require 'generator) | |
;;; utils | |
(defmacro with-time-elapse (&rest BODY) | |
`(let ((begin-time (current-time))) | |
,@BODY | |
(- (float-time (current-time)) (float-time begin-time)))) | |
;;; generator | |
(iter-defun fibonacci1 () | |
(let ((a 0) | |
(b 1)) | |
(while t | |
(iter-yield a) | |
(cl-psetq a b | |
b (+ a b))))) | |
;;; simulate generator | |
(defvar fibonacci4--a 0) | |
(defvar fibonacci4--b 1) | |
(defun fibonacci4 () | |
(let ((a fibonacci4--a)) | |
(setq fibonacci4--a fibonacci4--b | |
fibonacci4--b (+ a fibonacci4--b)) | |
a)) | |
;;; iteration | |
;; https://rosettacode.org/wiki/Fibonacci_sequence#Emacs_Lisp | |
(defun fibonacci2 (n &optional fn) | |
(let ( (vec) (i) (j) (k) ) | |
(if (< n 2) n | |
(progn | |
(setq vec (make-vector (+ n 1) 0) i 0 j 1 k 2) | |
(setf (aref vec 1) 1) | |
(when fn (funcall fn 0)) | |
(while (<= k n) | |
(setf (aref vec k) (+ (elt vec i) (elt vec j) )) | |
(when fn (funcall fn (aref vec j))) | |
(setq i (+ 1 i) j (+ 1 j) k (+ 1 k) )) | |
(elt vec n))))) | |
;;; recursion | |
;; https://rosettacode.org/wiki/Fibonacci_sequence#Emacs_Lisp | |
(defun fib (n a b c) | |
(if (< c n) (fib n b (+ a b) (+ 1 c) ) | |
(if (= c n) b a) )) | |
(defun fibonacci3 (n) (if (< n 2) n (fib n 0 1 1) )) | |
;;; tests | |
(let ((time1 0) | |
(time2 0) | |
(time3 0) | |
(time4 0)) | |
(dotimes (i 1000) (setq time3 (+ time3 (with-time-elapse (fibonacci3 100))))) | |
(dotimes (i 1000) (setq time2 (+ time2 (with-time-elapse (fibonacci2 100 (lambda (n) n)))))) | |
(dotimes (i 1000) (setq time1 (+ time1 (with-time-elapse | |
(cl-loop repeat 100 | |
for n iter-by (fibonacci1) | |
collect n))))) | |
(dotimes (i 1000) (setq time4 (+ time4 (with-time-elapse | |
(setq fibonacci4--a 0) | |
(setq fibonacci4--b 1) | |
(cl-loop repeat 100 | |
for n = (fibonacci4) | |
collect n))))) | |
(princ (format "fibonacci1 [generator]: %.6fs\n" time1)) | |
(princ (format "fibonacci2 [iteration]: %.6fs\n" time2)) | |
(princ (format "fibonacci3 [recursion]: %.6fs\n" time3)) | |
(princ (format "fibonacci4 [generat0r]: %.6fs\n" time4))) | |
;;; test-fibonacci.el ends here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test result: