File: fibonacci-test.lisp

package info (click to toggle)
cl-contextl 1%3A20231021.git3d5fbff-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 336 kB
  • sloc: lisp: 3,148; makefile: 2
file content (54 lines) | stat: -rw-r--r-- 1,326 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
(in-package :contextl-user)

;; pure Common Lisp version

(defvar *fib-cache*)

(defun fib1 (n)
  (or (gethash n *fib-cache*)
      (setf (gethash n *fib-cache*)
            (if (< n 2)
                1
              (+ (fib1 (- n 1))
                 (fib1 (- n 2)))))))

;; ContextL version

(define-layered-function fib2 (n))

(define-layered-method fib2 (n)
  (if (< n 2)
      1
    (+ (fib2 (- n 1))
       (fib2 (- n 2)))))

(deflayer fibonacci-cache)

(define-layered-method fib2
  :in fibonacci-cache (n)
  (or (gethash n *fib-cache*)
      (setf (gethash n *fib-cache*)
            (call-next-method))))

(defconstant +runs+ 10000000)
(defconstant +mod+ 1000)

(defun run-fib-test ()
  (print "Timing pure Common Lisp version.")
  (setf *fib-cache* (make-hash-table))
  (time (loop for i below +runs+
              do (fib1 (mod i +mod+))))

  (print "Timing ContextL version with global context switch.")
  (setf *fib-cache* (make-hash-table))
  (time (with-active-layers (fibonacci-cache)
          (loop for i below +runs+
                do (fib2 (mod i +mod+)))))

  (print "Timing ContextL version with local context switches.")
  (setf *fib-cache* (make-hash-table))
  (time (loop for i below +runs+
              do (with-active-layers (fibonacci-cache)
                   (fib2 (mod i +mod+)))))

  'done)