Is there a way to measure the amount of memory a program uses?

Hi all, I am wondering is there a way we can measure the memory consumption of a program 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]
    (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")

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

For datastructures there is GitHub - clojure-goes-fast/clj-memory-meter: Measure object memory consumption from Clojure</title

For looking at the actual heap usage, I would use
Looking at the process’s memory usage isn’t going to tell you how much is reserved vs. actually in use by the heap.

It looks like you have a non tail-recursive function call there too fyi. If you can convert it to a tail recursive version it could be constant space.

1 Like

You can use ThreadMXBean to measure memory allocated by a thread: