Skip to content

Instantly share code, notes, and snippets.

@ChrisBlom
Created June 2, 2016 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisBlom/9c7d1e98659f2048c66e19e932a9fa90 to your computer and use it in GitHub Desktop.
Save ChrisBlom/9c7d1e98659f2048c66e19e932a9fa90 to your computer and use it in GitHub Desktop.
;; 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