Skip to content

Instantly share code, notes, and snippets.

@hausdorff
Last active August 29, 2015 13:58
Show Gist options
  • Save hausdorff/10342678 to your computer and use it in GitHub Desktop.
Save hausdorff/10342678 to your computer and use it in GitHub Desktop.
;; This is a brief example of how introspective and intercessory functionality
;; can be encapsulated in a method combination without changing method
;; definitions or client code. Different implementations of the same method are
;; chosen randomly at runtime and the method combination profiles them to learn
;; which ones are more efficient and starts to call them more often than the
;; others.
(defgeneric sleep-and-stuff ()
(:method-combination adaptive-optimizer
;; You can easily create an interface to parameterize a
;; method combination like a higher-order function.
:sensitivity 11
:optimizer-type :moving-average
:max-history 1000)
(:method ()
(sleep (+ 0.003 (* (random-uniform) 0.001))))
(:method
;; The method combination can looks for special patterns in method
;; qualifiers to provide special new functionality beyond the standard
;; :before, :after, and :around combination style
:alt :v1
()
(sleep (+ 0.006 (* (random-uniform) 0.001))))
(:method :alt :v2 ()
(sleep (+ 0.007 (* (random-uniform) 0.001))))
(:method :alt :v3 ()
(sleep (+ 0.008 (* (random-uniform) 0.001))))
(:method :alt :v4 ()
(sleep (+ 0.011 (* (random-uniform) 0.001))))
(:method :before ()
(format *debug-output*
"Standard :before, :after, and :around methods can still be used...~%"))
(:method :after ()
(format *debug-output*
"... for debugging or whatever.~%")))
;; sample client code:
(iter (for i from 1 to 1000)
(sleep-and-stuff))
;; sample result after 1000 calls (the audience will see these numbers changing live at runtime):
;; call probability | average execution time | number of calls | method variant
.93865| 4.02159| 935.0|NIL
.03407| 7.34107| 36.0|(ALT V1)
.01964| 7.98063| 19.0|(ALT V2)
.00682| 9.26465| 7.0|(ALT V3)
.00082| 12.00000| 2.0|(ALT V4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment