Time method and print memory use in Scala

The following code will print out how long a method takes, return it’s value, and print out how much memory it consumed.

Example:

[info] Elapsed time (solr): 1.207055231s (solr)
[info] Memory: (solr): -33MB
[info] Elapsed time (tokenize): 1.091507079s (tokenize)
[info] Memory: (tokenize): -50MB
[info] Elapsed time (df): 3.809766467s (df)
[info] Memory: (df): -38MB
[info] Elapsed time (vectors): 19.631056498s (vectors)
[info] Memory: (vectors): -698MB
  val runtime = Runtime.getRuntime()
  val format = NumberFormat.getInstance()

  def time[R](name: String, block: => R): R = {
    val maxMemory1 = runtime.maxMemory()
    val allocatedMemory1 = runtime.totalMemory()
    val freeMemory1 = runtime.freeMemory()
    val totalFree1 = freeMemory1 + (maxMemory1 - allocatedMemory1)

    val t0 = System.nanoTime()
    val result = block
    val t1 = System.nanoTime()

    val maxMemory2 = runtime.maxMemory()
    val allocatedMemory2 = runtime.totalMemory()
    val freeMemory2 = runtime.freeMemory()
    val totalFree2 = freeMemory2 + (maxMemory2 - allocatedMemory2)

    println(
      "Elapsed time (" + name + "): " + (t1 - t0) / 1000000000.0 + "s (" + name + ")" + "\n" +
      "Memory: (" + name + "): " + format.format((totalFree2 - totalFree1) / 1024 / 1024) + "MB"
    )

    result
  }

Leave a Reply

Your email address will not be published. Required fields are marked *