Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to measure how much memory a Clojure program uses?

How can I measure, how much memory a Clojure program uses?

I've noted that even small programs, that say make something like

(println "Hello World")

can consume tens of megabytes of RAM, according to time (GNU time), ps and other tools like that.

Is there any correct method to detect how much memory a Clojure program really need?

How can I limit memory usage for a Clojure program? Is it possible to say something like "take no more than 1 MB"?

like image 721
Igor Chubin Avatar asked Oct 06 '14 09:10

Igor Chubin


1 Answers

Clojure runs on the JVM, so you can check how much memory it uses and limit its memory the same way you do it in Java.

Check memory usage:

final double freeMemory = Runtime.getRuntime().freeMemory() / (double) 1024;
final double totalMemory = Runtime.getRuntime().totalMemory() / (double) 1024;
final double usedMemory = totalMemory - freeMemory;

In Clojure (please forgive my poor idiom skills, still a beginner with Clojure)

(float (/ (- (-> (java.lang.Runtime/getRuntime) (.totalMemory)) (-> (java.lang.Runtime/getRuntime) (.freeMemory))) 1024))

(you can translate easily to Clojure with Java interop, not sure if there are already Clojure libraries for this).

Limit JVM maximum memory:

java -Xmx<memory>

For example: java -Xmx1024m will limit JVM to 1 GiB.

like image 157
m0skit0 Avatar answered Nov 15 '22 09:11

m0skit0