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

1

6

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

Malka answered 6/10, 2014 at 9:33 Comment(4)
Clojure's memory footprint is constrained by the size of the JVM. Clojure is a great language, but if you specifically need a program that runs in under 1MB, you should look at other languages.Lonnie
@user100464: Ok, you are maybe right, but what about say 20MB?Malka
I suggest you write Clojure program that prints "hello world" and then pauses on a read or a Thread sleep or something. While it is paused, use the available OS tools to see how much memory is being used.Lonnie
@user100464: Why so complex? You can just do time -v, or use jmap, that is not the problem at all. The question is how can I get my program under 20MBMalka
A
7

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.

Antilles answered 6/10, 2014 at 11:16 Comment(3)
The default is 1G unless you have more than 4GB ram in which it will limit to 25% of physical memory.Coss
To be clear, the -Xmx switch controls how much heap the JVM uses. It does not control the total memory footprint. If the OP is interested in running in under 1MB (or even 20MB), non-heap memory is going to be important too.Lonnie
not sure whether the OP actually asked about how much his code takes v.s. how much is allocated by the JVM, but in the latter case, IMO no need to subtract the memory used from the memory allocated.Fullbodied

© 2022 - 2024 — McMap. All rights reserved.