Skip to content

Instantly share code, notes, and snippets.

@canni
Last active October 5, 2017 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save canni/edfd680de012b544d5094d1164594365 to your computer and use it in GitHub Desktop.
Save canni/edfd680de012b544d5094d1164594365 to your computer and use it in GitHub Desktop.
Go like benchmark function for Kotlin
import kotlin.system.measureTimeMillis
fun benchmarkIt(msg: String, block: (Int) -> Unit) {
var n = 1
var duration: Long
do {
duration = measureTimeMillis { repeat(n, block) }
n *= 2
} while (duration < 100L)
val nsPerOp = duration.toDouble() * 1000 / n.toDouble()
println(
"%s ran %d operations in %d milliseconds; avg: %.3f ns/op".format(
msg, n, duration, nsPerOp
)
)
}
// Outputs (on my machine):
// String interpolation ran 8388608 operations in 191 milliseconds; avg: 0.023 ns/op
// String concatenation ran 8388608 operations in 172 milliseconds; avg: 0.021 ns/op
fun main(args: Array<String>) {
benchmarkIt("String interpolation") {
"String $it interpolation"
}
benchmarkIt("String concatenation") {
"String " + it + " concatenation"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment