Skip to content

Instantly share code, notes, and snippets.

@sherpc
Last active April 30, 2019 22:05
Show Gist options
  • Save sherpc/16e10aa2953c9e7a03da8ecc60dfe29a to your computer and use it in GitHub Desktop.
Save sherpc/16e10aa2953c9e7a03da8ecc60dfe29a to your computer and use it in GitHub Desktop.
Clojure simple memory usage log
(defn total-memory
[]
(.totalMemory (Runtime/getRuntime)))
(defn free-memory
[]
(.freeMemory (Runtime/getRuntime)))
(def steps
(->> ["B" "KB" "MB" "GB" "TB"]
(map vector (iterate #(* 1024.0 %) 1))
reverse))
(defn pprint-memory
[mem]
(some (fn [[s p]]
(when (> mem s)
(format "%.2f %s" (/ mem s) p)))
steps))
(defn start-memory-log
"Usage: (start-memory-log \"memory.txt\" 5) -- log memory for five seconds, store result in file 'memory.txt'. Runs in non-blocking thread."
[out-path seconds-to-run]
(future
(->> (range seconds-to-run)
(map (fn [_]
(Thread/sleep 1000)
[(total-memory) (free-memory) (- (total-memory) (free-memory))]))
(into [])
(map (fn [m] (->>
m
(map pprint-memory)
(clojure.string/join ", "))))
(clojure.string/join "\n")
(spit out-path))))
(defn current-pid
[]
(-> (java.lang.management.ManagementFactory/getRuntimeMXBean)
(.getName)
(clojure.string/split #"@")
(first)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment