Can we measure the memory consumed by a single function?

Hi all, I am wondering is there a way we can measure the memory consumption of a function in Clojure.
Let’s say this is an algorithm for finding the Levenshtein Distance

(defn cost [a b]
  (if (= a b) 0 1))

(defn levenshtein-distance 
  "Calculates the edit-distance between two sequences"
  [seq1 seq2]
  (cond
    (empty? seq1) (count seq2)
    (empty? seq2) (count seq1)
    :else (min
           (+ (cost (first seq1) (first seq2)) (levenshtein-distance (rest seq1) (rest seq2))) ;; substitution
           (inc (levenshtein-distance (rest seq1) seq2))    ;; insertion
           (inc (levenshtein-distance seq1 (rest seq2)))))) ;; deletion

This works:

user> (levenshtein-distance "kitten" "sitting")
  3

How to know how much memory this function (levenshtein-distance) has consumed? Thanks in advance. Just this function?

You can often get a reasonably accurate memory picture by making a ‘time’ like macro that does a GC before invoking your function and then consults memory statistics afterward. It’s more complicated than that, and if a GC ran while your function was running it would likely invalidate any meaningful numbers. Still, I’ve done this for small things, it can usefully tell you, for example, how much memory is used by a particular allocation.

You can query various memory properties via the java runtime: e.g.
(Runtime/getRuntime), (ManagementFactory/getGarbageCollectorMXBeans).
(ManagementFactory/getMemoryMXBean), (ManagementFactory/getMemoryPoolMXBeans)

And then digging through the information they contained. I’ve used this in the past to emulate a common-lisp like (room t) function.

Here’s an example using ThreadMXBean: https://github.com/jumarko/clojure-experiments/blob/master/src/clojure_experiments/performance/memory.clj#L139-L198