Lambda 用於對函式呼叫進行基準測試

通用秒錶,用於計算功能執行的時間:

object Benchmark {
    fun realtime(body: () -> Unit): Duration {
        val start = Instant.now()
        try {
            body()
        } finally {
            val end = Instant.now()
            return Duration.between(start, end)
        }
    }
}

用法:

val time = Benchmark.realtime({
    // some long-running code goes here ...
})
println("Executed the code in $time")