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

Bozhidar Batsov
  • 55,802
  • 13
  • 100
  • 117
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
  • 1
    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. – user100464 Oct 06 '14 at 12:16
  • @user100464: Ok, you are maybe right, but what about say 20MB? – Igor Chubin Oct 06 '14 at 14:32
  • 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. – user100464 Oct 06 '14 at 14:40
  • @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 20MB – Igor Chubin Oct 06 '14 at 14:42

1 Answers1

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.

Community
  • 1
  • 1
m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • The default is 1G unless you have more than 4GB ram in which it will limit to 25% of physical memory. – Sylwester Oct 06 '14 at 13:53
  • 1
    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. – user100464 Oct 06 '14 at 14:38
  • 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. – matanster Mar 30 '18 at 12:21