Igor Chubin
Igor Chubin

Reputation: 64563

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"?

Upvotes: 6

Views: 3256

Answers (1)

m0skit0
m0skit0

Reputation: 25863

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.

Upvotes: 8

Related Questions