How to measure function execution time in Scala

1 Answer

0 votes
// Measuring function execution time in 
// Scala using a reusable Timer (milliseconds + seconds)

object MeasureTimeWithTimer {

  // ---------------------------
  // Reusable Timer class
  // ---------------------------
  class Timer {
    private var start: Long = 0L
    private var end: Long = 0L

    // Start the timer
    def startTimer(): Unit = {
      start = System.nanoTime() // high‑precision timer
    }

    // Stop the timer
    def stopTimer(): Unit = {
      end = System.nanoTime()
    }

    // Return elapsed time in milliseconds
    def elapsedMilliseconds(): Double = {
      (end - start) / 1_000_000.0
    }

    // Return elapsed time in seconds
    def elapsedSeconds(): Double = {
      (end - start) / 1_000_000_000.0
    }
  }

  // ---------------------------
  // Function to measure
  // ---------------------------
  def work(): Unit = {
    var sum: Long = 0L
    for (i <- 0 until 100_000_000) {
      sum += i
    }
  }

  // ---------------------------
  // Main program
  // ---------------------------
  def main(args: Array[String]): Unit = {
    val t = new Timer()

    t.startTimer()
    work()
    t.stopTimer()

    val ms: Double = t.elapsedMilliseconds()
    val sec: Double = t.elapsedSeconds()

    println(s"Execution time: $ms ms")
    println(s"Execution time: $sec seconds")
  }
}



/* 
run:

Execution time: 307.03587 ms
Execution time: 0.30703587 seconds

*/

 



answered 2 hours ago by avibootz
...