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")