How to measure function execution time in Kotlin

1 Answer

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

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

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

    // Stop the timer
    fun stopTimer() {
        end = System.nanoTime()
    }

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

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

// ---------------------------
// Function to measure
// ---------------------------
fun work() {
    var sum = 0L
    for (i in 0 until 100_000_000) {
        sum += i
    }
}

// ---------------------------
// Main program
// ---------------------------
fun main() {
    val t = Timer()

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

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

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



/* 
run:

Execution time: 39.686506 ms
Execution time: 0.039686506 seconds

*/

 



answered 3 hours ago by avibootz
...