Created
June 2, 2016 13:23
-
-
Save ChrisBlom/9c7d1e98659f2048c66e19e932a9fa90 to your computer and use it in GitHub Desktop.
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
;; Toggle a counter that tracks how manny times a function is called | |
(defn instrument-fn [f] | |
(let [counter (atom 0)] | |
(-> (fn [& args] ;; NOTE could unroll for 1-n args for speed | |
(swap! counter inc) | |
(apply f args)) | |
(with-meta | |
{:uninstrumented f | |
:counter counter})))) | |
(defn toggle-fn-instrumentation | |
[f] | |
(assert (fn? f) "Only fns can be instrumented") | |
(let [{:keys [counter uninstrumented]} (meta f)] | |
(if uninstrumented | |
uninstrumented | |
(instrument-fn f)))) | |
(defn toggle-counter [fn-var] | |
(alter-var-root fn-var toggle-fn-instrumentation)) | |
(defn foo [] (println "FOO")) | |
(foo) | |
(some-> foo meta :counter deref) | |
(toggle-counter #'foo) | |
(some-> foo meta :counter deref) | |
(dotimes [_ 5] | |
(foo)) | |
(some-> foo meta :counter deref) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment