2

I am trying to find the memory usage of a Scala program I am even getting the result. I am referring the following code:

object Test {
    def main(args: Array[String]): Unit = {
        val mb = 1024*1024
        val runtime = Runtime.getRuntime
        println("\nMemory in MB")
        println("** Used Memory:  " + (runtime.totalMemory - runtime.freeMemory)/mb)
        println("** Free Memory:  " + runtime.freeMemory/mb)
        println("** Total Memory: " + runtime.totalMemory/mb)
        println("** Max Memory:   " + runtime.maxMemory/mb)
    }
}

Output is as follows:

Memory in MB - 
** Used Memory:  2
** Free Memory:  28
** Total Memory: 31
** Max Memory:   228

However, how accurate is the result that this code is using 2MB memory? Is there a better way to do such bench-marking?

vinzee93
  • 91
  • 7
  • How is this related to Java? – RaminS Dec 09 '16 at 21:33
  • Because "Runtime.getRuntime" is a java method ported to Scala. – vinzee93 Dec 09 '16 at 21:35
  • You are using integers for your calculations so you have already lost some precision. You might want to use a profiling tool; even jvisualvm has good monitoring and graphing capabilities. – Bob Dalgleish Dec 09 '16 at 21:50
  • @BobDalgleish - Even after removing the integers the memory usage is around 2MB. – vinzee93 Dec 09 '16 at 22:04
  • DId find this link which answers the high values - [high-java-memory-usage-even-for-small-programs](http://stackoverflow.com/questions/13692206/high-java-memory-usage-even-for-small-programs) – vinzee93 Dec 09 '16 at 22:06
  • @vinzee93 You mistake me. You were using integer arithmetic, which causes subtle and not-so-subtle rounding errors. This fundamentally affects the accuracy of your results. That being said, you also need to understand that you are "benchmarking" an outlier, and all you can really do is use it as a baseline. The results are not meaningful unless compared with other benchmarks. – Bob Dalgleish Dec 12 '16 at 12:44

0 Answers0